我已经尝试使用pgmex。不幸的是,它无法与libpq5配合使用(matlab立即崩溃)。
如果不使用数据库工具箱,可以通过类似以下方式从 Matlab 连接到 Postgres:
% Add jar file to classpath (ensure it is present in your current dir)
javaclasspath('postgresql-9.0-801.jdbc4.jar');
% Username and password you chose when installing postgres
props=java.util.Properties;
props.setProperty('user', '<your_postgres_username>');
props.setProperty('password', '<your_postgres_password>');
% Create the database connection (port 5432 is the default postgres chooses
% on installation)
driver=org.postgresql.Driver;
url = 'jdbc:postgresql://<yourhost>:<yourport>\<yourdb>';
conn=driver.connect(url, props);
% A test query
sql='select * from <table>'; % Gets all records
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
% Read the results into an array of result structs
count=0;
result=struct;
while rs.next()
count=count+1;
result(count).var1=char(rs.getString(2));
result(count).var2=char(rs.getString(3));
...
end
props.setProperty('ssl','true');
而不是如Matlab帮助中所说的使用SSLFactory...的正常URL。
所以这很好,但我不能使用数据库工具箱的函数...嗯,也不是很重要!
花了我一些时间才发现这一点,所以也许对于其他人有用的是,如果他们也遇到在SSL模式下连接远程数据库的问题。
谢谢!
(免责声明:需要数据库工具箱)
这是一个完整的示例,展示了如何从Matlab脚本中准备好设置PostgreSQL服务器,请根据需要调整数据库参数:
%Set preferences with setdbprefs.
setdbprefs('DataReturnFormat', 'cellarray');
setdbprefs('NullNumberRead', 'NaN');
setdbprefs('NullStringRead', 'null');
%Make connection to database.
%Using JDBC driver.
conn = database('mydb', 'USERNAME', 'YOURPASSWORD', 'Vendor',...
'POSTGRESQL', 'Server', 'SERVERIP', 'PortNumber', 5432);
%Read data from database, just an example on weather table in mydb database
curs = exec(conn, ['SELECT weather.city'...
' , weather.temperature'...
' FROM "mydb"."public".weather ']);
curs = fetch(curs);
close(curs);
%Assign data to output variable
untitled = curs.Data;
%Close database connection.
close(conn);
%Clear variables
clear curs conn
你的用户需要具备登录权限角色,并能够访问表格( GRANT)。