1. 主要流程
参考来源 https://stackoverflow.com/questions/2698159/how-can-i-access-a-postgresql-database-from-matlab-with-without-matlabs-database
% 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
rs.close()
注意:需要根据系统使用的JDK版本下载合适的jar版本(示例中使用的是postgresql-9.0-801.jdbc4.jar),否则无法成功连接数据库。版本参照 https://jdbc.postgresql.org/download.html
2.SQL语句
进行条件搜索时使用问号?作为占位符,然后使用setObject函数替换。详细内容查看https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
具体用法如下:
...
foovalue = 500;
st = conn.prepareStatement("SELECT * FROM mytable WHERE columnfoo = ?");
st.setObject(1, foovalue);
rs = st.executeQuery();
...
模糊查询,限制数目等sql语法可以参照https://www.tutorialspoint.com/postgresql/index.htm