云服务器内容精选

  • 执行普通SQL语句 应用程序通过执行SQL语句来操作数据库的数据(不用传递参数的语句),需要按以下步骤执行: 调用Connection的createStatement方法创建语句对象。 1 Statement stmt = con.createStatement(); 调用Statement的executeUpdate方法执行SQL语句。 1 int rc = stmt.executeUpdate("CREATE EXTERNAL TABLE newproducts(product_id INTEGER,product_name VARCHAR2(60),category VARCHAR2(60),quantity INTEGER)STORE AS orc;"); 数据库中收到的一次执行请求(不在事务块中),如果含有多条语句,将会被打包成一个事务,事务块中不支持vacuum操作。如果其中有一个语句失败,那么整个请求都将会被回滚。 关闭语句对象。 1 stmt.close();
  • 执行预编译SQL语句 预编译语句是只编译和优化一次,然后可以通过设置不同的参数值多次使用。由于已经预先编译好,后续使用会减少执行时间。因此,如果多次执行一条语句,请选择使用预编译语句。可以按以下步骤执行: 调用Connection的prepareStatement方法创建预编译语句对象。 1 PreparedStatement pstmt = con.prepareStatement("select * from newproducts where product_id = ?"); 调用PreparedStatement的setShort设置参数。 1 pstmt.setString(1, "1502"); 调用PreparedStatement的executeUpdate方法执行预编译SQL语句。 1 ResultSet resultSet = pstmt.executeQuery(); 调用PreparedStatement的close方法关闭预编译语句对象。 1 pstmt.close();
  • 执行批处理 用一条预处理语句处理多条相似的数据,数据库只创建一次执行计划,节省了语句的编译和优化时间。可以按如下步骤执行: 调用Connection的prepareStatement方法创建预编译语句对象。 1 PreparedStatement pstmt = con.prepareStatement("INSERT INTO newproducts VALUES (?, ?, ?, ?);"); 针对每条数据都要调用setShort设置参数,以及调用addBatch确认该条设置完毕。 1 2 3 4 5 preparedStatement.setInt(1, 1); preparedStatement.setString(2, "name"); preparedStatement.setString(3, "cata"); preparedStatement.setInt(4, 1); preparedStatement.addBatch(); 调用PreparedStatement的executeBatch方法执行批处理。 1 int[] rowcount = pstmt.executeBatch(); 调用PreparedStatement的close方法关闭预编译语句对象。 1 pstmt.close(); 在实际的批处理过程中,通常不终止批处理程序的执行,否则会降低数据库的性能。因此在批处理程序时,应该关闭自动提交功能,每几行提交一次。关闭自动提交功能的语句为:conn.setAutoCommit(false);
  • JDBC接口参考 JDBC接口是一套提供给用户的API方法,本节将对部分常用接口做具体描述,如果涉及其他接口可参考JDK1.6(软件包)/JDBC4.0中相关内容。 java.sql.Connection java.sql.DatabaseMetaData java.sql.Driver java.sql.PreparedStatement java.sql.ResultSet java.sql.ResultSetMetaData java.sql.Statement javax.sql.ConnectionPoolDataSource javax.sql.DataSource javax.sql.PooledConnection javax.naming.Context javax.naming.spi.InitialContextFactory 父主题: 基于JDBC开发
  • 示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 //以下用例以gsjdbc4.jar为例。 //以下代码将获取数据库连接操作封装为一个接口,可通过给定用户名和密码来连接数据库。 public static Connection getConnect(String username, String passwd) { //驱动类。 String driver = "org.postgresql.Driver"; //数据库连接描述符。 String sourceURL = "jdbc:postgresql://$ip:$port/postgres"; Connection conn = null; try { //加载驱动。 Class.forName(driver); } catch( Exception e ) { e.printStackTrace(); return null; } try { //创建连接。 conn = DriverManager.getConnection(sourceURL, username, passwd); System.out.println("Connection succeed!"); } catch(Exception e) { e.printStackTrace(); return null; } return conn; } // 以下代码将使用Properties对象作为参数建立连接 public static Connection getConnectUseProp(String username, String passwd) { //驱动类。 String driver = "org.postgresql.Driver"; //数据库连接描述符。 String sourceURL = "jdbc:postgresql://$ip:$port/postgres?autoBalance=true"; Connection conn = null; Properties info = new Properties(); try { //加载驱动。 Class.forName(driver); } catch( Exception e ) { e.printStackTrace(); return null; } try { info.setProperty("user", userName); info.setProperty("password", password); //创建连接。 conn = DriverManager.getConnection(sourceURL, info); System.out.println("Connection succeed!"); } catch(Exception e) { e.printStackTrace(); return null; } return conn; }
  • 参数 表1 数据库连接参数 参数 描述 url gsjdbc4.jar数据库连接描述符。格式如下: jdbc:postgresql:database jdbc:postgresql://host/database(端口值缺省会使用默认端口) jdbc:postgresql://host:port/database jdbc:postgresql://host:port/database?param1=value1¶m2=value2 jdbc:postgresql://host1:port1,host2:port2/database?param1=value1¶m2=value2 说明: 使用gsjdbc200.jar时,将“jdbc:postgresql”修改为“jdbc:gaussdb” database为要连接的数据库名称。 host为数据库服务器名称或IP地址。 由于安全原因,数据库CN禁止集群内部其他节点无认证接入。如果要在集群内部访问CN,请将JDBC程序部署在CN所在机器,host使用"127.0.0.1"。否则可能会出现“FATAL: Forbid remote connection with trust method!”错误。 建议业务系统单独部署在集群外部,否则可能会影响数据库运行性能。 缺省情况下,连接服务器为localhost。 port为数据库服务器端口。 缺省情况下,会尝试连接到5431端口的database。 param为参数名称,即数据库连接属性。 参数可以配置在URL中,以"?"开始配置,以"="给参数赋值,以"&"作为不同参数的间隔。也可以采用info对象的属性方式进行配置,详细示例会在本节给出。 value为参数值,即数据库连接属性值。 连接时需配置connectTimeout和socketTimeout,如果未配置,默认为0,即不会超时。在DN与客户端出现网络故障时,客户端一直未收到DN侧ACK确认报文,会启动超时重传机制,不断地进行重传。当重传次数达到默认的15次后才会报超时错误,会导致RTO时间很高。 分布式环境下,连接串建议配置autoBalance参数进行负载均衡,同时配置至少两个CN节点,避免因节点故障无法正常建连。 info 数据库连接属性(所有属性大小写敏感)。常用的属性如下: PGDBNAME:String类型。表示数据库名称(URL中无需配置该参数,自动从URL中解析)。 PGHOST:String类型。主机IP地址。若配置多个CN,它们的IP和端口用“:”分隔,并作为整体以逗号分隔其他CN(URL中无需配置该参数,自动从URL中解析)。 PGPORT:Integer类型。主机端口号。若配置多个CN,它们的端口号和IP用":"分隔,并作为整体以逗号分隔其他CN(URL中无需配置该参数,自动从URL中解析)。 user:String类型。表示创建连接的数据库用户。 password:String类型。表示数据库用户的密码。 loggerLevel:String类型。缺省值为NULL,与设置为INFO等效。目前支持4种级别:OFF、INFO、DEBUG、TRACE。设置为OFF关闭日志。设置为INFO、DEBUG和TRACE记录的日志信息详细程度不同。 loggerFile:String类型。用于指定日志输出路径(目录和文件名)。若只指定文件名,未指定目录则日志生成在客户端运行程序目录;若不配置或配置的路径不存在,则日志会默认通过流输出。此参数已废弃,不再生效,如需使用可通过 java.util.logging 属性文件或系统属性进行配置。 logger:String类型。表示JDBC Driver要使用的日志输出框架。JDBC Driver支持对接用户应用程序使用的日志输出框架。目前支持的第三方日志输出框架只有基于Slf4j-API的日志框架。具体使用方式,见6.2.9日志管理。 如果缺省或设置为JDK LOG GER,则JDBC Driver使用JDK LOGGER。 否则必须设置采用基于slf4j-API 第三方日志框架。 allowEncodingChanges:Boolean类型,缺省值为false。设置该参数值为“true”进行字符集类型更改,配合参数characterEncoding=CHARSET设置字符集,二者使用"&"分隔;characterEncoding取值范围{UTF8、GBK、LATIN1、GB18030}。 currentSchema:String类型。在search-path中指定要设置的schema。如果Schema名包含除字母、数字、下划线之外的特殊字符,建议在Schema名上加引号,注意加引号后Schema名大小写敏感。如需配置多个Schema,要用逗号(,)进行分隔,包含特殊字符的Schema也需要加引号处理。 例如:currentSchema=schema_a,"schema-b","schema/c"。 loadBalanceHosts:Boolean类型。在默认模式下(禁用),顺序连接URL中指定的多个主机。如果启用,则使用洗牌算法从候选主机中随机选择一个主机建立连接。 autoBalance:String类型。 设置为true或balance或roundrobin表示开启JDBC负载均衡功能,将应用程序的多个连接均衡到数据库集群中的各个可用CN。 例如:jdbc:postgresql://host1:port1,host2:port2/database?autoBalance=true JDBC将定期获取(周期刷新可使用参数refreshCNIpListTime配置,默认为10s)整个集群可用CN列表(注意CN列表中获取的host是数据IP),比如获取到的列表为:host1:port1,host2:port2,host3:port3,host4:port4。 host1和host2在autoBalance启用时,仅在首次连接做高可用用途,后续Driver将从host1,host2,host3,host4中依次选择可用的CN刷新可用CN列表,后续用户新建的connection将使用RoundRobin算法从host1,host2,host3,host4选取CN主机进行连接。 设置为priorityn表示开启JDBC优先级负载均衡功能,将应用程序的多个连接首先均衡到url上配置的前n个中可用的CN数据库节点,当url上配置前n个节点全部不可用时,连接会随机分配到数据库集群中其他可用CN数据库节点。n为数字,不小于0,且小于url上配置的CN数量。 例如:jdbc:postgresql://host1:port1,host2:port2,host3:port3,host4:port4/database?autoBalance=priority2 JDBC将定期获取(周期按refreshCNIpListTime定义)整个集群可用CN列表,比如获取到的列表为:host1:port1,host2:port2,host3:port3,host4:port4,host5:port5,host6:port6,其中host1和host2处于AZ1,host3和host4处于AZ2。 Driver将从优先从host1,host2中做负载均衡,host1和host2全部不可用才从host3, host4, host5, host6中随机选择CN主机连接。 设置为shuffle表示开启JDBC随机负载均衡功能,将应用程序的多个连接随机均衡到数据库集群中的各个可用CN。 例如:jdbc:postgresql://host1:port1,host2:port2,host3:port3/database?autoBalance=shuffle JDBC将定期获取(周期刷新可使用参数refreshCNIpListTime配置,默认为10S)整个集群的可用CN列表,比如获取到的列表为:host1:port1,host2:port2,host3:port3,host4:port4。 host1:port1,host2:port2,host3:port3,仅在首次连接做高可用,后续连接将在刷新后的CN列表中,使用shuffle算法随机选用一个CN节点进行连接。 设置为false,不开启JDBC负载均衡功能和优先级负载均衡功能。默认为false。 注意: 负载均衡是基于连接级别,不是基于事务级别。如果连接是长连接,并且连接上的负载不均衡,无法保证CN主机上的负载是均衡的。 负载均衡仅能在分布式场景下使用。 在开启负载均衡时,URL中可以配置浮动IP或数据IP,如果配置为浮动IP,系统会根据浮动IP获取对应的数据IP,通过获取的数据IP做负载均衡。因此URL中配置浮动IP或数据IP时,都需要确保数据IP网络连接正常,否则负载均衡功能异常。 refreshCNIpListTime:Integer类型。获取CN列表的缓存有效时间。JDBC在建连时会检测数据库集群中CN状态,在refreshCNIpListTime时间内可信。超过则状态失效,下次建连时再次获取可用CN的IP列表。默认为10秒。 hostRecheckSeconds:Integer类型。JDBC尝试连接主机后会保存主机状态:连接成功或连接失败。在hostRecheckSeconds时间内保持可信,超过则状态失效。缺省值是10秒。 ssl:Boolean类型。以SSL方式连接。 ssl=true可支持NonValidatingFactory通道和使用证书的方式: 1、NonValidatingFactory通道需要配置用户名和密码,同时将SSL设置为true。 2、配置客户端证书、密钥、根证书,将SSL设置为true。 sslmode:String类型。SSL认证方式。取值范围为:disable、allow、prefer、require、verify-ca、verify-full。 disable:不使用SSL安全连接。 allow:如果数据库服务器要求使用,则可以使用SSL安全加密连接,但不验证数据库服务器的真实性。 prefer:如果数据库支持,那么首选使用SSL连接,但不验证数据库服务器的真实性。 require只尝试SSL连接,不会检查服务器证书是否由受信任的CA签发,且不会检查服务器主机名与证书中的主机名是否一致。 verify-ca只尝试SSL连接,并且验证服务器是否具有由可信任的证书机构签发的证书。 verify-full只尝试SSL连接,并且验证服务器是否具有由可信任的证书机构签发的证书,以及验证服务器主机名是否与证书中的一致。 sslcert:String类型。提供证书文件的完整路径。客户端和服务端证书的类型为End Entity。 sslkey:String类型。提供密钥文件的完整路径。如果客户端证书不是DER格式,使用时将客户端证书转换为DER格式,生成方式参考连接数据库(以SSL方式)章节。 sslrootcert:String类型。SSL根证书的文件名。根证书的类型为CA。 sslpassword:String类型。提供给ConsoleCallbackHandler使用。 sslpasswordcallback:String类型。SSL密码提供者的类名。缺省值:org.postgresql.ssl.jdbc4.LibPQFactory.ConsoleCallbackHandler。 sslfactory:String类型。提供的值是SSLSocketFactory在建立SSL连接时用的类名。 sslprivatekeyfactory: String类型。提供的值是实现私钥解密方法的接口org.postgresql.ssl.PrivateKeyFactory的实现类的完整限定类名。如果不提供,首先尝试默认的jdk私钥解密算法,如果无法解密,则使用org.postgresql.ssl.BouncyCastlePrivateKeyFactory,用户需要自己提供bcpkix-jdk15on.jar包,版本建议:1.65以上。 sslfactoryarg:String类型。此值是上面提供的sslfactory类的构造函数的可选参数(不推荐使用本参数)。 sslhostnameverifier:String类型。主机名验证程序的类名。接口实现javax.net.ssl.HostnameVerifier,默认使用org.postgresql.ssl.PGjdbcHostnameVerifier。 loginTimeout:Integer类型。指建立数据库连接的等待时间。超时时间单位为秒。当url配置多IP时,若获取连接花费的时间超过此值,则连接失败,不再尝试后续IP。 connectTimeout:Integer类型。用于连接服务器操作的超时值。如果连接到服务器花费的时间超过此值,则连接断开。超时时间单位为秒,值为0时表示已禁用,timeout不发生。当url配置多IP时,表示连接单个IP的超时时间。 socketTimeout:Integer类型。用于socket读取操作的超时值。如果从服务器读取所花费的时间超过此值,则连接关闭。超时时间单位为秒,值为0时表示已禁用,timeout不发生。 当JDBC侧触发超时且连接关闭时,其下发给数据库侧正在运行的业务会被强制终止。该能力受GUC参数check_disconnect_query控制,设置为on表示支持该能力,设置为off表示不支持该能力。 socketTimeoutInConnecting:Integer类型。用于控制建立连接阶段socket读取操作的超时值。如果建立连接时从服务器读取所花费的时间超过此值,则查找下一个节点建立连接。超时时间单位为秒,默认为5s。 driverInfoMode:String类型。用于控制驱动描述信息的输出模式。取值范围为postgresql、gaussdb,默认缺省值为postgresql,输出postgresql相关的驱动描述信息;设置为gaussdb时输出gaussdb相关的驱动描述信息。 cancelSignalTimeout:Integer类型。发送取消消息本身可能会阻塞,用于控制取消命令的“connect超时”和“socket超时”。如果取消命令超过指定时间未响应,会中断这个连接,减少占用客户端资源。超时时间单位为秒,默认值为10秒。 tcpKeepAlive:Boolean类型。启用或禁用TCP保活探测功能。默认为false。 logUnclosedConnections:Boolean类型,缺省值为false。客户端可能由于未调用Connection对象的close()方法而泄漏Connection对象。最终这些对象将被垃圾回收,并且调用finalize()方法。设置为true之后,如果调用者自己忽略了此操作,该方法将关闭Connection。 assumeMinServerVersion(废弃):String类型。该参数设置要连接的服务器版本。 ApplicationName:String类型。设置正在使用连接的应用程序名称。通过在CN上查询pgxc_stat_activity表可以看到正在连接的客户端信息,显示在application_name列。缺省值为PostgreSQL JDBC Driver。 connectionExtraInfo:Boolean类型。表示驱动是否上报当前驱动的部署路径、进程属主用户、url连接配置信息到数据库。 取值范围:true或false,默认值为false。设置connectionExtraInfo为true,JDBC驱动会将当前驱动的部署路径、进程属主用户、url连接配置信息上报到数据库中,记录在connection_info参数里;同时可以在PG_STAT_ACTIVITY和PGXC_STAT_ACTIVITY中查询到。 autosave:String类型。共有3种:"always", "never", "conservative"。如果查询失败,指定驱动程序应该执行的操作。在autosave=always模式下,JDBC驱动程序在每次查询之前设置一个保存点,并在失败时回滚到该保存点。在autosave=never模式(默认)下,无保存点。在autosave=conservative模式下,每次查询都会设置保存点,但是只会在“statement XXX无效”等情况下回滚并重试。 protocolVersion:Integer类型。连接协议版本号,目前仅支持1和3。注意:设置1时仅代表连接的是V1服务端。设置3时将采用md5加密方式,需要同步修改数据库的加密方式,将GUC参数password_encryption_type设置为1,重启数据库生效后需要创建用md5方式加密口令的用户。同时修改pg_hba.conf,将客户端连接方式修改为md5。用新建用户进行登录(因为设置这个值后,只能使用低等级的加密方式(md5),降低安全性,所以此值不推荐设置)。 说明: MD5加密算法安全性低,存在安全风险,建议使用更安全的加密算法。 prepareThreshold:Integer类型。该值决定着PreparedStatement对象在执行多少次以后使用服务端已经准备好的statement。默认值是5,意味着在执行同一个PreparedStatement对象时,在第五次以及以上执行时不再向服务端发送parse消息对statement进行解析,而使用之前在服务端已经解析好的statement。 preparedStatementCacheQueries:Integer类型。该参数确定了每个连接的cache缓存Statement对象生成query的最大个数。默认值为256,若Statement对象生成query个大于256则会将最近最少使用的query从缓存中丢弃。0表示禁用缓存。 preparedStatementCacheSizeMiB:Integer类型,该参数确定了每个连接的cache缓存Statement对象所生成query的最大值(以兆字节为单位),默认情况下是5。若缓存了超过5MB的query,则最近最少使用的查询缓存将被丢弃。0表示禁用缓存。 databaseMetadataCacheFields:Integer类型。默认值是65536。指定每个连接可缓存的最大字段的个数。“0”表示禁用缓存。 databaseMetadataCacheFieldsMiB:Integer类型。默认值是5。指定每个连接可缓存的字段的最大值,单位是MB。“0”表示禁用缓存。 stringtype:String类型,可选字段为:"unspecified", "varchar"。设置通过setString()方法使用的PreparedStatement参数的类型,如果stringtype设置为VARCHAR(默认值),则这些参数将作为varchar参数发送给服务器。若stringtype设置为unspecified,则参数将作为untyped值发送到服务器,服务器将尝试推断适当的类型。 batchMode:String类型。用于确定是否使用batch模式连接。默认值为on,表示开启batch模式。设置batchMode=on执行成功的返回结果为[count, 0, 0...0],数组第一个元素为批量影响的总条数,设置batchMode=off执行成功的返回结果为[1, 1, 1...1],数组各元素对应单次修改的影响条数。 fetchsize:Integer类型。用于设置数据库连接所创建statement的默认fetchsize。默认值为0,表示一次获取所有结果。与defaultRowFetchSize等价,如果同时设置,以fetchsize为准。 reWriteBatchedInserts:Boolean类型。批量导入时,该参数设置为true,可将N条插入语句合并为一条:insert into TABLE_NAME values(values1, ..., valuesN), ..., (values1, ..., valuesN);使用该参数时,需设置batchMode=off。 unknownLength:Integer类型,默认为Integer.MAX_VALUE。某些PostgreSQL类型(例如TEXT)没有明确定义的长度,当通过ResultSetMetaData.getColumnDisplaySize和ResultSetMetaData.getPrecision等函数返回关于这些类型的数据时,此参数指定未知长度类型的长度。 defaultRowFetchSize:Integer类型。确定一次fetch在ResultSet中读取的行数。限制每次访问数据库时读取的行数可以避免不必要的内存消耗,从而避免OutOfMemoryException。缺省值是0,这意味着ResultSet中将一次获取所有行。本参数不允许设置为负值。 binaryTransfer:Boolean类型。使用二进制格式发送和接收数据,默认值为“false”。 binaryTransferEnable:String类型。启用二进制传输的类型列表,以逗号分隔。OID编号和名称二选一,例如binaryTransferEnable=INT4_ARRAY,INT8_ARRAY。 比如:OID名称为BLOB,编号为88,可以如下配置: binaryTransferEnable=BLOB 或 binaryTransferEnable=88 binaryTransferDisable:String类型。禁用二进制传输的类型列表,以逗号分隔。OID编号和名称二选一。覆盖binaryTransferEnable的设置。 blobMode:String类型。用于设置setBinaryStream方法绑定参数的数据类型,当该值为on时表示setBinaryStream绑定的数据类型为blob类型,为off时表示绑定的数据类型为bytea类型,默认为on。建议从Oracle、Mysql迁移来的系统将该值设定为on,从PostgreSQL迁移来的系统设定为off。 socketFactory:String类型。用于创建与服务器socket连接的类的名称。该类必须实现接口“javax.net.SocketFactory”,并定义无参或单String参数的构造函数。 socketFactoryArg:String类型。此值是上面提供的socketFactory类的构造函数的可选参数,不推荐使用。 receiveBufferSize:Integer类型。该值用于设置连接流上的SO_RCVBUF。 sendBufferSize:Integer类型。该值用于设置连接流上的SO_SNDBUF。 preferQueryMode:String类型。共有4种:"extended", "extendedForPrepared", "extendedCacheEverything", "simple"。用于指定执行查询的模式,默认值为extended。simple模式只发送Q消息,仅支持文本模式,不支持parse与bind;extended模式会使用parse、bind和execute消息;extendedForPrepared模式下只有Prepared Statement对象使用扩展查询,Statement对象只使用简单查询;extendedCacheEverything模式会缓存每个Statement对象所生成的query。 ApplicationType:String类型。共有2种:"not_perfect_sharding_type","perfect_sharding_type"。用于设置是否开启分布式写入和查询,默认值为"not_perfect_sharding_type"。not_perfect_sharding_type模式下开启分布式写入和查询;perfect_sharding_type模式下默认禁止分布式写入和查询,只有在sql文中加入/* multinode */ 才能执行分布式写入和查询。该项设置只有数据库处于gtm free场景的情况下才会有效。 priorityServers:Integer类型。此值用于指定url上配置的前n个节点作为主集群被优先连接。默认值为null。该值为数字,大于0,且小于url上配置的CN数量。用于流式容灾场景。 例如:jdbc:postgresql://host1:port1,host2:port2,host3:port3,host4:port4,/database?priorityServers=2。即表示host1与host2为主集群节点,host3与host4为容灾集群节点。 usingEip:Boolean类型。此值用于控制是否使用弹性公网IP做负载均衡。默认值为true,表示使用弹性公网IP做负载均衡;false表示使用数据IP做负载均衡。 traceInterfaceClass:String类型。默认值为null,用于获取traceId的实现类。值是实现获取traceId方法的接口org.postgresql.log.Tracer的实现类的完整限定类名。 use_boolean:Boolean类型。用于设置extended模式下setBoolean方法绑定的oid类型,默认为false,绑定int2类型;设置为true则绑定bool类型。 allowReadOnly:Boolean类型。用于设置是否允许只读模式,默认为true,允许设置只读模式;设置为false则禁用只读模式。 TLSCiphersSupperted:String类型。用于设置支持的TLS加密套件,默认为TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384。 stripTrailingZeros:Boolean类型。默认值为false,设置为true则去除numeric类型后尾随的0,仅对ResultSet.getObject(int columnIndex)生效。 enableTimeZone:Boolean类型。默认值为true,用于指定是否启用服务端时区设置,true表示获取JVM时区指定数据库时区,false表示使用数据库时区。 socketTimeoutInConnecting:Integer类型。默认值5s,用于建立连接时socket读取操作的超时值。如果在建连过程中,从服务器读取所花费的时间超过此值,则连接关闭。超时时间单位为秒,值为0时表示已禁用,timeout不发生。 driverInfoMode:String类型。用于控制驱动描述信息的输出模式。取值范围为postgresql、gaussdb,默认缺省值为postgresql,输出PostgreSQL相关的驱动描述信息,设置为gaussdb时输出gaussdb相关的驱动描述信息。 user 数据库用户。 password 数据库用户的密码。
  • JDBC接口参考 JDBC接口是一套提供给用户的API方法,本节将对部分常用接口做具体描述,若涉及其他接口可参考JDK1.8(软件包)/JDBC4.2中相关内容。 java.sql.Connection java.sql.CallableStatement java.sql.DatabaseMetaData java.sql.Driver java.sql.PreparedStatement java.sql.ResultSet java.sql.ResultSetMetaData java.sql.Statement javax.sql.ConnectionPoolDataSource javax.sql.DataSource javax.sql.PooledConnection javax.naming.Context javax.naming.spi.InitialContextFactory CopyManager PGReplicationConnection PGReplicationStream ChainedStreamBuilder ChainedCommonStreamBuilder PGobject 父主题: 基于JDBC开发
  • JDBC接口参考 JDBC接口是一套提供给用户的API方法,本节将对部分常用接口做具体描述,若涉及其他接口可参考JDK1.8(软件包)/JDBC 4.2中相关内容。 java.sql.Connection java.sql.CallableStatement java.sql.DatabaseMetaData java.sql.Driver java.sql.PreparedStatement java.sql.ResultSet java.sql.ResultSetMetaData java.sql.Statement javax.sql.ConnectionPoolDataSource javax.sql.DataSource javax.sql.PooledConnection javax.naming.Context javax.naming.spi.InitialContextFactory CopyManager PGReplicationConnection PGReplicationStream ChainedStreamBuilder ChainedCommonStreamBuilder 父主题: 基于JDBC开发
  • JDBC包 从管理控制台下载包名为dws_8.1.x_jdbc_driver.zip。 请参见下载JDBC或ODBC驱动。 解压后有两个JDBC的驱动jar包: gsjdbc4.jar:与PostgreSQL保持兼容的驱动包,其中类名、类结构与PostgreSQL驱动完全一致,曾经运行于PostgreSQL的应用程序可以直接移植到当前系统使用。 gsjdbc200.jar:如果同一JVM进程内需要同时访问PostgreSQL及 GaussDB (DWS)请使用此驱动包,它的主类名为“com.huawei.gauss200.jdbc.Driver”(即将“org.postgresql”替换为“com.huawei.gauss200.jdbc”),数据库连接的URL前缀为“jdbc:gaussdb”,其余与gsjdbc4.jar相同。
  • 从MySQL向GaussDB(DWS)进行数据迁移 下面示例演示如何通过CopyManager从mysql向GaussDB(DWS)进行数据迁移的过程。 以下用例以gsjdbc4.jar为例,如果要使用gsjdbc200.jar,请替换驱动类名(将代码中的“org.postgresql”替换成“com.huawei.gauss200.jdbc”)与连接URL串前缀(将“jdbc:postgresql”替换为“jdbc:gaussdb”)。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 import java.io.StringReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; public class Migration{ public static void main(String[] args) { String url = new String("jdbc:postgresql://10.180.155.74:8000/gaussdb"); //数据库URL String user = new String("jack"); //DWS用户名 String pass = new String("********"); //DWS密码 String tablename = new String("migration_table"); //定义表信息 String delimiter = new String("|"); //定义分隔符 String encoding = new String("UTF8"); //定义字符集 String driver = "org.postgresql.Driver"; StringBuffer buffer = new StringBuffer(); //定义存放格式 化数据的缓存 try { //获取源数据库查询结果集 ResultSet rs = getDataSet(); //遍历结果集,逐行获取记录 //将每条记录中各字段值,按指定分隔符分割,由换行符结束,拼成一个字符串 //把拼成的字符串,添加到缓存buffer while (rs.next()) { buffer.append(rs.getString(1) + delimiter + rs.getString(2) + delimiter + rs.getString(3) + delimiter + rs.getString(4) + "\n"); } rs.close(); try { //建立目标数据库连接 Class.forName(driver); Connection conn = DriverManager.getConnection(url, user, pass); BaseConnection baseConn = (BaseConnection) conn; baseConn.setAutoCommit(false); //初始化表信息 String sql = "Copy " + tablename + " from STDIN DELIMITER " + "'" + delimiter + "'" + " ENCODING " + "'" + encoding + "'"; //提交缓存buffer中的数据 CopyManager cp = new CopyManager(baseConn); StringReader reader = new StringReader(buffer.toString()); cp.copyIn(sql, reader); baseConn.commit(); reader.close(); baseConn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(System.out); } catch (SQLException e) { e.printStackTrace(System.out); } } catch (Exception e) { e.printStackTrace(); } } 从源数据库返回查询结果集: private static ResultSet getDataSet() { ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://10.119.179.227:3306/jack?useSSL=false&allowPublicKeyRetrieval=true", "jack", "********"); Statement stmt = conn.createStatement(); rs = stmt.executeQuery("select * from migration_table"); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return rs; } }
  • 通过本地文件导入导出数据 在使用JAVA语言基于GaussDB(DWS)进行二次开发时,可以使用CopyManager接口,通过流方式,将数据库中的数据导出到本地文件或者将本地文件导入数据库中,文件格式支持 CS V、TEXT等格式。 样例程序如下,执行时需要加载GaussDB(DWS) jdbc驱动。 以下用例以gsjdbc4.jar为例,如果要使用gsjdbc200.jar,请替换驱动类名(将代码中的“org.postgresql”替换成“com.huawei.gauss200.jdbc”)与连接URL串前缀(将“jdbc:postgresql”替换为“jdbc:gaussdb”)。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import java.sql.Connection; import java.sql.DriverManager; import java.io.IOException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.sql.SQLException; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; public class Copy{ public static void main(String[] args) { String urls = new String("jdbc:postgresql://10.180.155.74:8000/gaussdb"); //数据库URL String username = new String("jack"); //用户名 String password = new String("********"); //密码 String tablename = new String("migration_table"); //定义表信息 String tablename1 = new String("migration_table_1"); //定义表信息 String driver = "org.postgresql.Driver"; Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(urls, username, password); } catch (ClassNotFoundException e) { e.printStackTrace(System.out); } catch (SQLException e) { e.printStackTrace(System.out); } 执行数据导入导出: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 // 将migration_table查询结果导出到本地文件d:/data.txt try { copyToFile(conn, "d:/data.txt", "(SELECT * FROM migration_table)"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //将d:/data.txt中的数据导入到migration_table_1中。 try { copyFromFile(conn, "d:/data.txt", migration_table_1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 将migration_table_1中的数据导出到本地文件d:/data1.txt try { copyToFile(conn, "d:/data1.txt", migration_table_1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void copyFromFile(Connection connection, String filePath, String tableName) throws SQLException, IOException { FileInputStream fileInputStream = null; try { CopyManager copyManager = new CopyManager((BaseConnection)connection); fileInputStream = new FileInputStream(filePath); copyManager.copyIn("COPY " + tableName + " FROM STDIN", fileInputStream); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void copyToFile(Connection connection, String filePath, String tableOrQuery) throws SQLException, IOException { FileOutputStream fileOutputStream = null; try { CopyManager copyManager = new CopyManager((BaseConnection)connection); fileOutputStream = new FileOutputStream(filePath); copyManager.copyOut("COPY " + tableOrQuery + " TO STDOUT", fileOutputStream); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
  • 示例2 客户端内存占用过多解决 此示例主要使用setFetchSize来调整客户端内存使用,它的原理是通过数据库游标来分批获取服务器端数据,但它会加大网络交互,可能会损失部分性能。 由于游标事务内有效,故需要先关闭自动提交。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // 关闭掉自动提交 conn.setAutoCommit(false); Statement st = conn.createStatement(); // 打开游标,每次获取50行数据 st.setFetchSize(50); ResultSet rs = st.executeQuery("SELECT * FROM mytable"); while (rs.next()){ System.out.print("a row was returned."); } rs.close(); // 关闭服务器游标。 st.setFetchSize(0); rs = st.executeQuery("SELECT * FROM mytable"); while (rs.next()){ System.out.print("many rows were returned."); } rs.close(); // Close the statement. st.close();
  • 通过本地文件导入导出数据 在使用JAVA语言基于GaussDB(DWS)进行二次开发时,可以使用CopyManager接口,通过流方式,将数据库中的数据导出到本地文件或者将本地文件导入数据库中,文件格式支持CSV、TEXT等格式。 样例程序如下,执行时需要加载GaussDB(DWS) jdbc驱动。 以下用例以gsjdbc4.jar为例,如果要使用gsjdbc200.jar,请替换驱动类名(将代码中的“org.postgresql”替换成“com.huawei.gauss200.jdbc”)与连接URL串前缀(将“jdbc:postgresql”替换为“jdbc:gaussdb”)。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import java.sql.Connection; import java.sql.DriverManager; import java.io.IOException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.sql.SQLException; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; public class Copy{ public static void main(String[] args) { String urls = new String("jdbc:postgresql://10.180.155.74:8000/gaussdb"); //数据库URL String username = new String("jack"); //用户名 String password = new String("********"); //密码 String tablename = new String("migration_table"); //定义表信息 String tablename1 = new String("migration_table_1"); //定义表信息 String driver = "org.postgresql.Driver"; Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(urls, username, password); } catch (ClassNotFoundException e) { e.printStackTrace(System.out); } catch (SQLException e) { e.printStackTrace(System.out); } 执行数据导入导出: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 // 将migration_table查询结果导出到本地文件d:/data.txt try { copyToFile(conn, "d:/data.txt", "(SELECT * FROM migration_table)"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //将d:/data.txt中的数据导入到migration_table_1中。 try { copyFromFile(conn, "d:/data.txt", migration_table_1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 将migration_table_1中的数据导出到本地文件d:/data1.txt try { copyToFile(conn, "d:/data1.txt", migration_table_1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void copyFromFile(Connection connection, String filePath, String tableName) throws SQLException, IOException { FileInputStream fileInputStream = null; try { CopyManager copyManager = new CopyManager((BaseConnection)connection); fileInputStream = new FileInputStream(filePath); copyManager.copyIn("COPY " + tableName + " FROM STDIN", fileInputStream); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void copyToFile(Connection connection, String filePath, String tableOrQuery) throws SQLException, IOException { FileOutputStream fileOutputStream = null; try { CopyManager copyManager = new CopyManager((BaseConnection)connection); fileOutputStream = new FileOutputStream(filePath); copyManager.copyOut("COPY " + tableOrQuery + " TO STDOUT", fileOutputStream); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
  • 从MySQL向GaussDB(DWS)进行数据迁移 下面示例演示如何通过CopyManager从mysql向GaussDB(DWS)进行数据迁移的过程。 以下用例以gsjdbc4.jar为例,如果要使用gsjdbc200.jar,请替换驱动类名(将代码中的“org.postgresql”替换成“com.huawei.gauss200.jdbc”)与连接URL串前缀(将“jdbc:postgresql”替换为“jdbc:gaussdb”)。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 import java.io.StringReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; public class Migration{ public static void main(String[] args) { String url = new String("jdbc:postgresql://10.180.155.74:8000/gaussdb"); //数据库URL String user = new String("jack"); //DWS用户名 String pass = new String("********"); //DWS密码 String tablename = new String("migration_table"); //定义表信息 String delimiter = new String("|"); //定义分隔符 String encoding = new String("UTF8"); //定义字符集 String driver = "org.postgresql.Driver"; StringBuffer buffer = new StringBuffer(); //定义存放格式 化数据的缓存 try { //获取源数据库查询结果集 ResultSet rs = getDataSet(); //遍历结果集,逐行获取记录 //将每条记录中各字段值,按指定分隔符分割,由换行符结束,拼成一个字符串 //把拼成的字符串,添加到缓存buffer while (rs.next()) { buffer.append(rs.getString(1) + delimiter + rs.getString(2) + delimiter + rs.getString(3) + delimiter + rs.getString(4) + "\n"); } rs.close(); try { //建立目标数据库连接 Class.forName(driver); Connection conn = DriverManager.getConnection(url, user, pass); BaseConnection baseConn = (BaseConnection) conn; baseConn.setAutoCommit(false); //初始化表信息 String sql = "Copy " + tablename + " from STDIN DELIMITER " + "'" + delimiter + "'" + " ENCODING " + "'" + encoding + "'"; //提交缓存buffer中的数据 CopyManager cp = new CopyManager(baseConn); StringReader reader = new StringReader(buffer.toString()); cp.copyIn(sql, reader); baseConn.commit(); reader.close(); baseConn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(System.out); } catch (SQLException e) { e.printStackTrace(System.out); } } catch (Exception e) { e.printStackTrace(); } } 从源数据库返回查询结果集: private static ResultSet getDataSet() { ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://10.119.179.227:3306/jack?useSSL=false&allowPublicKeyRetrieval=true", "jack", "********"); Statement stmt = conn.createStatement(); rs = stmt.executeQuery("select * from migration_table"); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return rs; } }
  • 示例2 客户端内存占用过多解决 此示例主要使用setFetchSize来调整客户端内存使用,它的原理是通过数据库游标来分批获取服务器端数据,但它会加大网络交互,可能会损失部分性能。 由于游标事务内有效,故需要先关闭自动提交。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // 关闭掉自动提交 conn.setAutoCommit(false); Statement st = conn.createStatement(); // 打开游标,每次获取50行数据 st.setFetchSize(50); ResultSet rs = st.executeQuery("SELECT * FROM mytable"); while (rs.next()){ System.out.print("a row was returned."); } rs.close(); // 关闭服务器游标。 st.setFetchSize(0); rs = st.executeQuery("SELECT * FROM mytable"); while (rs.next()){ System.out.print("many rows were returned."); } rs.close(); // Close the statement. st.close();