MATLAB 2013a connect to postgresql use jdbc

本文涉及的产品
云数据库 RDS SQL Server,基础系列 2核4GB
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
云原生数据库 PolarDB MySQL 版,通用型 2核4GB 50GB
简介:
matlab的安装请参考 : 
本文将介绍如何使用matlab通过jdbc连接PostgreSQL数据库.
首先要确认java版本 : 
pg90@db-172-16-3-150-> java -version
java version "1.7.0_09-icedtea"
OpenJDK Runtime Environment (rhel-2.3.4.1.el6_3-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)

然后到  http://jdbc.postgresql.org/  下载java版本对应的postgresql jdbc驱动.
[root@db-172-16-3-150 soft_bak]# wget http://jdbc.postgresql.org/download/postgresql-9.2-1003.jdbc4.jar

将这个驱动拷贝到matlab的本地目录
[root@db-172-16-3-150 jar]# cd /opt/matlab/2013a/java/jar
[root@db-172-16-3-150 jar]# cp /opt/soft_bak/postgresql-9.2-1003.jdbc4.jar ./
[root@db-172-16-3-150 local]# cd /opt/matlab/2013a/toolbox/local

把这个驱动加到matlab的classpath.txt配置文件中.
[root@db-172-16-3-150 local]# vi classpath.txt
# Java classpath entries for shared_controllib_general
$matlabroot/java/jar/toolbox/shared/controllib.jar

在这行后面添加如下 : 
# Java classpath entries for postgresql
$matlabroot/java/jar/postgresql-9.2-1003.jdbc4.jar

启动matlab查看classpath配置是否生效
[root@db-172-16-3-150 ~]# matlab -nodesktop -nodisplay
                                                      < M A T L A B (R) >
                                            Copyright 1984-2013 The MathWorks, Inc.
                                              R2013a (8.1.0.604) 64-bit (glnxa64)
                                                       February 15, 2013
To get started, type one of these: helpwin, helpdesk, or demo.
For product information, visit www.mathworks.com.
 
>> javaclasspath  
        ......... 略 , 可以看到已经加载了postgresql jdbc驱动文件
        /opt/matlab/2013a/java/jar/toolbox/shared/controllib.jar                           
        /opt/matlab/2013a/java/jar/postgresql-9.2-1003.jdbc4.jar   

在数据库中创建测试表和测试数据.
pg90@db-172-16-3-150-> psql
psql (9.0.13)
Type "help" for help.
digoal=# create role digoal nosuperuser login encrypted password 'digoal123';
CREATE ROLE
digoal=# grant all on database digoal to digoal;
GRANT
digoal=# \c digoal digoal
You are now connected to database "digoal" as user "digoal".
digoal=> create schema digoal authorization digoal;
CREATE SCHEMA
digoal=> create table test(id int , info text , crt_time timestamp);
CREATE TABLE
digoal=> insert into test select generate_series(1,1000), md5(random()::text), clock_timestamp();
INSERT 0 1000

在matlab中连接postgresql数据库
[root@db-172-16-3-150 ~]# matlab -nodesktop -nodisplay
                                                      < M A T L A B (R) >
                                            Copyright 1984-2013 The MathWorks, Inc.
                                              R2013a (8.1.0.604) 64-bit (glnxa64)
                                                       February 15, 2013
To get started, type one of these: helpwin, helpdesk, or demo.
For product information, visit www.mathworks.com.
不要模仿以下连接方式, 有问题.
>> conn = database('digoal', 'digoal', 'digoal123', 'org.postgresql.Driver', 'jdbc:postgresql://127.0.0.1:1999/digoal?connect_timeout=10&application_name=myapp')

在PostgreSQL中可以查到这个连接.
postgres=# select * from pg_stat_activity;
-[ RECORD 1 ]----+--------------------------------
datid            | 16384
datname          | digoal
procpid          | 6070
usesysid         | 24576
usename          | digoal
application_name | 
client_addr      | 127.0.0.1
client_port      | 59559
backend_start    | 2013-09-27 16:08:07.019998+08
xact_start       | 
query_start      | 2013-09-27 16:08:07.052041+08
waiting          | f
current_query    | <IDLE>

但是url中的其他参数( ?connect_timeout=10&application_name=myapp' )未生效, 所以就不需要指定了.
并且由于第一个参数就是库名, 所以url中的库名也不需要.
例如, 以下方式连接 反而有问题.

>> conn = database('abc', 'digoal', 'digoal123', 'org.postgresql.Driver', 'jdbc:postgresql://127.0.0.1:1999/digoal')
 abc和 digoal 叠加了.
conn =
 
       Instance: 'abc'
       UserName: 'digoal'
         Driver: []
            URL: []
    Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
        Message: 'FATAL: database "digoalabc" does not exist'
         Handle: 0
        TimeOut: 0
     AutoCommit: 'off'
           Type: 'Database Object'

正确的连接应该是 : 
>> conn = database('digoal', 'digoal', 'digoal123', 'org.postgresql.Driver', 'jdbc:postgresql://127.0.0.1:1999/')
 
conn =
 
       Instance: 'digoal'
       UserName: 'digoal'
         Driver: 'org.postgresql.Driver'
            URL: 'jdbc:postgresql://127.0.0.1:1999/'
    Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
        Message: []
         Handle: [1x1 org.postgresql.jdbc4.Jdbc4Connection]
        TimeOut: 0
     AutoCommit: 'on'
           Type: 'Database Object'

从数据库中获取数据.
建立游标

>> curs = exec(conn, ['select * from test'])       
 
curs =
 
        Attributes: []
              Data: 0
    DatabaseObject: [1x1 database]
          RowLimit: 0
          SQLQuery: 'select * from test'
           Message: []
              Type: 'Database Cursor Object'
         ResultSet: [1x1 org.postgresql.jdbc4.Jdbc4ResultSet]
            Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]
         Statement: [1x1 org.postgresql.jdbc4.Jdbc4Statement]
             Fetch: 0

从游标中获取10条记录
>> row = fetch(curs, 10)
row =
 
        Attributes: []
              Data: {10x3 cell}
    DatabaseObject: [1x1 database]
          RowLimit: 0
          SQLQuery: 'select * from test'
           Message: []
              Type: 'Database Cursor Object'
         ResultSet: [1x1 org.postgresql.jdbc4.Jdbc4ResultSet]
            Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]
         Statement: [1x1 org.postgresql.jdbc4.Jdbc4Statement]
             Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

打印行
>> row.[TAB可以补齐]
attr            columnnames     Data            fetch           querytimeout    rows            subsasgn        
Attributes      Contents        DatabaseObject  fetchmulti      ResultSet       set             subsref         
close           cursor          dbtbx           get             rowlimit        SQLQuery        Type            
cols            Cursor          Fetch           Message         RowLimit        Statement       width           

>> row.Data
ans = 

    [ 1]    'fb16393ce8dddeb794a84df08224bdd3'    '2013-09-27 16:00:20.089714'
    [ 2]    '3323f8b123975444440b68142b2ff662'    '2013-09-27 16:00:20.089879'
    [ 3]    'be14e9e0a6e5e3bde71d88769d630be5'    '2013-09-27 16:00:20.089889'
    [ 4]    '5d495efd2777df0c973e8dbe121566b3'    '2013-09-27 16:00:20.089895'
    [ 5]    '07a2f7a23698a1460d5b9f56ee65bf17'    '2013-09-27 16:00:20.089901'
    [ 6]    'ec89d2ab88f874b4967e954132514a45'    '2013-09-27 16:00:20.089907'
    [ 7]    '2f73aa414f6001e9f70f97e7deba328e'    '2013-09-27 16:00:20.089913'
    [ 8]    '459e2aa0ca1e4515372eaa9ab7053af1'    '2013-09-27 16:00:20.089918'
    [ 9]    'e74da999ec0de81cd577d776e61a63a4'    '2013-09-27 16:00:20.089924'
    [10]    'a548ec8602b8bdc53b379404fbf9f529'    '2013-09-27 16:00:20.08993' 

关闭游标和数据库连接
>> help /cursor/close
 CLOSE Close cursor.
    CLOSE(CURSOR) closes the database cursor.
    CURSOR is a cursor structure with all elements defined.
 
    See also FETCH.

    Reference page in Help browser
       doc database/close
>> help /database/close
 CLOSE Close database connection.
    CLOSE(CONNECT) closes the database connection.
    CONNECT is a database connection object returned by 
    DATABASE.
   
    See also DATABASE.

    Reference page in Help browser
       doc database/close

所有数据库相关帮助见本文末尾.
例如关闭数据库连接 : 

>> close(conn)
在数据库中就看不到matlab过来的连接了
postgres=# select * from pg_stat_activity;
 datid | datname  | procpid | usesysid | usename  | application_name | client_addr | client_port |         backend_start         |  
        xact_start          |         query_start          | waiting |          current_query          
-------+----------+---------+----------+----------+------------------+-------------+-------------+-------------------------------+--
----------------------------+------------------------------+---------+---------------------------------
 11826 | postgres |    5870 |       10 | postgres | psql             |             |          -1 | 2013-09-27 16:01:03.994593+08 | 2
013-09-27 16:20:57.09995+08 | 2013-09-27 16:20:57.09995+08 | f       | select * from pg_stat_activity;
(1 row)



[参考]
3. matlab 帮助
6. matlab help database

>> help database
  Database Toolbox
  Version 4.1 (R2013a) 13-Feb-2013
 
   General functions:
 
   chkprops      - Database object properties.
   logintimeout  - Set or get time allowed to establish database connection.
   setdbprefs    - Set preferences for database actions for handling null values.
   dexplore      - Configure, explore and import database data using Database Explorer
 
   Database Access functions:
 
   /database/catalogs           - Get database catalog names.
   /database/clearwarnings      - Clear warnings for database connection.
   /database/close              - Close database connection.
   /database/columns            - Get database table column names.
   /database/commit             - Make database changes permanent.
   /database/database           - Connect to database.
   /database/exec               - Execute SQL statement and open cursor.
   /database/fetch              - Import data into MATLAB using connection handle.
   /database/get                - Get database property.
   /database/insert             - Export MATLAB cell array data to database table.
   /database/isconnection       - Detect if database connection is valid.
   /database/isreadonly         - Detect if database connection is read-only.
   /database/ping               - Get status information about database connection.
   /database/rollback           - Undo database changes.
   /database/runstoredprocedure - Stored procedures with input and output parameters.
   /database/schemas            - Get database schema names.
   /database/set                - Set properties for database connection.
   /database/sql2native         - Convert JDBC SQL grammar into system's native SQL grammar.
   /database/tables             - Get database table names.
   /database/update             - Replace data in database table with data from MATLAB cell array.
 
   Database Cursor Access functions:
 
   /cursor/attr         - Get attributes of columns in fetched data set.
   /cursor/close        - Close cursor.
   /cursor/cols         - Get number of columns in fetched data set.
   /cursor/columnnames  - Get names of columns in fetched data set.
   /cursor/fetch        - Import data into MATLAB.
   /cursor/get          - Get property of cursor object.
   /cursor/querytimeout - Get time allowed for a database SQL query to succeed.
   /cursor/rows         - Get number of rows in fetched data set.
   /cursor/set          - Set RowLimit for cursor fetch.
   /cursor/width        - Get width of column in fetched data set.
 
   Database Toolbox Object functions:
 
   /dbtbx/dbtbx      - Construct Database Toolbox object.
   /dbtbx/display    - Database Toolbox object display method.
   /dbtbx/subsasgn   - Subscripted assignment for Database Toolbox object.
   /dbtbx/subsref    - Subscripted reference for Database Toolbox object.
 
   Database Toolbox Database MetaData functions:
 
   /dmd/bestrowid         - Get database table unique row identifier.
   /dmd/columnprivileges  - Get database column privileges.
   /dmd/columns           - Get database table column names.
   /dmd/crossreference    - Get information about primary and foreign keys.
   /dmd/dmd               - Construct database metadata object.
   /dmd/exportedkeys      - Get information about exported foreign keys.
   /dmd/get               - Get database metadata properties.
   /dmd/importedkeys      - Get information about imported foreign keys.
   /dmd/indexinfo         - Get indices and statistics for database table.
   /dmd/primarykeys       - Get primary key information for database table or schema.
   /dmd/procedurecolumns  - Get catalog's stored procedure parameters and result columns.
   /dmd/procedures        - Get catalog's stored procedures.
   /dmd/supports          - Detect if property is supported by database metadata.
   /dmd/tableprivileges   - Get database table privileges.
   /dmd/tables            - Get database table names.
   /dmd/versioncolumns    - Get automatically updated table columns.
 
   Database Toolbox Driver functions:
 
   /driver/driver     - Construct database driver object.
   /driver/get        - Get database driver properties.
   /driver/isdriver   - Detect if driver is a valid JDBC driver object.
   /driver/isjdbc     - Detect if driver is JDBC-compliant.
   /driver/isurl      - Detect if database URL is valid.
   /driver/register   - Load database driver.
   /driver/unregister - Unload database driver.
 
   Database Toolbox Drivermanager functions:
 
   /drivermanager/drivermanager  - Construct database drivermanager object.
   /drivermanager/get            - Get database drivermanager properties.
   /drivermanager/set            - Set database drivermanager properties.
 
   Database Toolbox Resultset functions:
 
   /resultset/clearwarnings  - Clear the warnings for the resultset.
   /resultset/close          - Close resultset object.
   /resultset/get            - Get resultset properties.
   /resultset/isnullcolumn   - Detect if last record read in resultset was null.
   /resultset/namecolumn     - Map resultset column name to resultset column index.
   /resultset/resultset      - Construct resultset object.
 
   Database Toolbox Resultset MetaData functions:
 
   /rsmd/rsmd  - Construct resultset metadata object.
   /rsmd/get   - Get resultset metadata properties.
 
   Database Toolbox bulk insert examples:
 
   /dbdemos/mssqlserverbulkinsert  - MS SQL Server bulk insert example. 
   /dbdemos/mysqlbulkinsert  - MySQL bulk insert example.
   /dbdemos/oraclebulkinsert - Oracle bulk insert example.
  
   Visual Query Builder functions:
 
   /vqb/confds              - Configure data source (UNIX only).
   /vqb/getdatasources      - Return valid data sources on system.
   /vqb/loginconnect        - Datasource connection.
   /vqb/parsebinary         - Write binary object to disk.
   /vqb/qbhelp              - Query Builder help string.
   /vqb/querybuilder        - Start visual SQL query builder.
   /vqb/showdata            - Display data in interactive window.
   /vqb/showdatacallbacks   - Visual Query Builder data display callbacks.
   /vqb/vqbdemo             - Visual Query Builder demonstrations.


database is both a directory and a function.

 DATABASE Connect to database.
    CONNECT = DATABASE(INSTANCE,USERNAME,PASSWORD)
    returns a database connection object. Connection is established using 
    an ODBC driver. INSTANCE is the name of the ODBC data source set up,
    USERNAME and PASSWORD are the required credentials for access to the 
    database.
 
    CONNECT = DATABASE(INSTANCE,USERNAME,PASSWORD,DRIVER,DATABASEURL) 
    returns a database connection object. Connection is established using a 
    JDBC driver. INSTANCE is the name of the database, USERNAME and 
    PASSWORD are the required credentials for access to the database.
    DRIVER is a JDBC driver name and DATABASEURL is the connection URL for 
    the database. 
 
    CONNECT = DATABASE(INSTANCE,USERNAME,PASSWORD,'PARAM','VALUE')
    returns a database connection object. Connection is established using a 
    JDBC driver. PARAM-VALUE pairs are:
 
    Parameter      Value                                        Default
    ---------      -----                                        -------
    VENDOR         Must be provided. Needs to be one of:        None 
                   'MySQL','Oracle','Microsoft SQL Server', 
                   'PostGreSQL'. Use this along with zero or 
                   more of the following params as required 
                   to establish a connection. If connecting 
                   to a database system not listed here,
                   use the DRIVER and DATABASEURL syntax
 
    SERVER         Name/Address of the database server          localhost
 
    PORTNUMBER     number of the port that the server           vendor 
                   is listening on                              specific 
 
    AUTHTYPE       one of:'Server','Windows'. Only valid        Server
                   for SQL Server. Specify 'Windows'
                   for Windows Authentication.
 
    DRIVERTYPE     one of: 'thin','oci'. Only valid for         None
                   Oracle.
 
    URL            Connection URL.If URL is specified,          None
                   no other properties may be required
                   
 
    
    Use LOGINTIMEOUT before DATABASE to set the maximum time for a
    connection attempt.
 
    Example:
 
    JDBC-ODBC connection:
 
    conn=database('oracle','scott','tiger')
 
    where:
 
    'oracle' is the ODBC datasource name for an ORACLE database.
    'scott'  is the user name.
    'tiger'  is the password.
 
 
    JDBC connection:
 
    conn=database('oracle','scott','tiger',
                 'oracle.jdbc.driver.OracleDriver','jdbc:oracle:oci7:')
 
    where:
 
    'oracle' is the database name.
    'scott'  is the user name.
    'tiger'  is the password.
    'oracle.jdbc.driver.OracleDriver' is the JDBC driver to be used
                                      to make the connection.
    'jdbc:oracle:oci7:' is the URL as defined by the Driver vendor
                        to establish a connection with the database.
  
    Using Param-Value pairs:
 
    conn=database('oracle','scott','tiger','Vendor', 'Oracle',
    'DriverType', 'oci', 'Server', 'remotehost', 'PortNumber', 1234)
 
    where:
 
    remotehost: Database Server machine name
    1234: Port Number which the server is listening on
 
    See also CLOSE.

    Reference page in Help browser
       doc database

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
目录
相关文章
|
存储 网络协议 Java
PostgreSQL JDBC 开发指导
Java Database Connectivity (JDBC) 是一个应用程序编程接口 (API),用于 编程语言 Java,它定义了客户端如何访问数据库。 它是Java标准版平台的一部分,提供查询和 更新数据库中的数据,并面向关系数据库。 PostgreSQL JDBC驱动程序(简称pgJDBC)允许Java程序连接到PostgreSQL®® 数据库使用标准的、独立于数据库的 Java 代码。是一个开源的JDBC驱动程序 用纯Java(类型4)编写,并使用PostgreSQL®本机网络协议进行通信。 因此,驱动程序独立于平台;编译后,驱动程序 可以在任何系统上使用。
179 0
|
SQL druid Java
Java 执行 Postgresql Jdbc 类型异常时,复杂sql难定位的解决方案
Java 执行 Postgresql Jdbc 类型异常时,复杂sql难定位的解决方案
1419 0
Java 执行 Postgresql Jdbc 类型异常时,复杂sql难定位的解决方案
|
Java 关系型数据库 数据库连接
|
关系型数据库 PostgreSQL
PostgreSQL sharding : citus 系列7 - topn 加速(count(*) group by order by count(*) desc limit x) (use 估值插件 topn)
标签 PostgreSQL , topn , topn.number_of_counters , count(*) group by order by count(*) desc limit x 背景 count(*) group by order by count(*) desc limit x 用来统计 topn。
1434 0
|
关系型数据库 PostgreSQL
PostgreSQL sharding : citus 系列6 - count(distinct xx) 加速 (use 估值插件 hll|hyperloglog)
标签 PostgreSQL , hll , hyperloglog , distinct , 加速 , citus.count_distinct_error_rate 背景 在分布式数据库中,计算count(distinct xxx),需要对distinct 的字段, 1、去重, 2、重分布去重后的数据,(这一步,如果distinct值特别多,那么就会比较耗时) 3、然后再去重, 4、最后count (xxx), 5、求所有节点的count SUM。
1839 0
|
弹性计算 关系型数据库 测试技术
PostgreSQL 11 tpcc 测试(103万tpmC on ECS) - use sysbench-tpcc by Percona-Lab
标签 PostgreSQL , tpcc 背景 环境 阿里云虚拟机 [root@pg11-test ~]# lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: ...
4409 0
|
Web App开发 监控 Java
|
关系型数据库 Java 数据库连接
|
SQL Java 关系型数据库
PostgreSQL jdbc driver的一个不完善之处
公司一个产品在上线到云以后,运行一段时间就会提示获取数据库连接失败,用 select * from pg_stat_activity; 查看所有连接,发现有很多连接最后一次执行的SQL语句是 SELECT t.typname,t.oid FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON (t.typspace = n.oid)  WHERE n.nspname  != 'pg_toast',经确认在程序中没有任何一处执行了该SQL。
1340 0