Setting up of Port forwarding to PostgreSQL from MATLAB

6 次查看(过去 30 天)
Hi,
I have a MATLAB script that I used to run by connecting to the postgres database that is hosted on the server(Openshift).
I used to do port forwarding using database toolbox and hardcode the port number (see below 60733) in the MATLAB script each time to connect to the database
I'd like to automate this process so that when I open MATLAB I can directly run the script without having to generate the port manually all the timet. Is there any way to automare this DB connection ?
Note : I'm using Openshift PostgreSQL databse server hence I need to port forward from my machine to connect to this server
I have used database toolbox to connect the server DB using below credentials
databasename = 'employeedb';
username = 'user';
password = 'user123';
driver = 'org.postgresql.Driver';
url = 'jdbc:postgresql://localhost:60733/employeedb';
conn = database(databasename,username,password,driver,url);
countSqlquery = "SELECT COUNT(*) as count_pet FROM employees";
rowCount = select(conn,countSqlquery);
  2 个评论
Manoj
Manoj 2023-2-8
To connect to a database hosted on server, there's a port number that we use. This is generated manually when the connection is established

请先登录,再进行评论。

回答(1 个)

Piyush Kumar
Piyush Kumar 2024-10-23,8:45
Hi,
You can automate port forwarding using ssh by executing the system command within MATLAB script.
For example,
% Automate port forwarding using SSH (example command)
% Adjust the SSH command as per your setup
system('ssh -L 60733:localhost:5432 user@remote_server -N &');
% Pause to ensure the port forwarding is established
pause(5);
To dynamically find an available port, you may use the following script:
startPort = 60000;
endPort = 60100;
freePort = -1; % Initialize with an invalid port number
for port = startPort:endPort
try
% Try to create a TCP/IP client object
t = tcpclient('localhost', port);
clear t; % Close and delete the client object if successful
freePort = port;
break;
catch
% If an error occurs, the port is not available
continue;
end
end
if freePort == -1
error('No free ports found in the specified range.');
end
Additionally, please ensure that SSH key-based authentication is set up for seamless connection without the need to enter a password each time. This can be done by adding your SSH key to the ~/.ssh/authorized_keys file on the remote server.

类别

Help CenterFile Exchange 中查找有关 Database Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by