mysql/jdbc:设置useInformationSchema=true读取表注释信息(table_comment)

#问题描述
今天在读取表的注释信息(COMMENT)时,发现返回的REMARKS字段返回居然是null.
以下是代码示例:

DatabaseMetaData meta = this.pConnection.getMetaData();
// 获取所有表信息
ResultSet resultSet = this.meta.getTables(this.catalog, tableSchema, pattern, this.tableTypes);
while (resultSet.next()) {
	Table table = new Table();
	# 返回null
	String comment=resultSet.getString("REMARKS");
}
resultSet.close();

#原因分析
google找了半天,总算知道原因:
Connector/J 5.0.0以后的版本有一个名为useInformationSchema的数据库连接参数,
在默认连接参数情况下,useInformationSchema=false,导致Connection.getMetaData()方法返回的DatabaseMetaData 对象是com.mysql.jdbc.DatabaseMetaData,而不是com.mysql.jdbc。DatabaseMetaDataUsingInfoSchema,
DatabaseMetaDataUsingInfoSchemaDatabaseMetaData是的子类,看名称就能联想到是通过 INFORMATION_SCHEMA 数据库获取数据库的metadata,可以正确返回table_comment字段。

下面是useInformationSchema的官方说明

useInformationSchema

When connected to MySQL-5.0.7 or newer, should the driver use the INFORMATION_SCHEMA to derive information used by DatabaseMetaData?

Default: false
Since version: 5.0.0
摘自《5.1 Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J》

而父类DatabaseMetaData并不一定能正常返回table_comment字段.

关于INFORMATION_SCHEMA 这里不深入探讨,参见《Chapter 24 INFORMATION_SCHEMA Tables》
#解决方法
解决的方法也很简单:
数据库连接时设置useInformationSchema=true
如何设置数据库连接参数呢?有两个途径
##方法一:java代码实现

# 将所有参数装入java.util.Properties 对象
Properties props = new Properties();
props.setProperty("username",this.username);
props.setProperty("password",this.password); 
props.setProperty("useInformationSchema", "true");
# 调用getConnection(String,Properties)方法创建连接
this.pConnection = java.sql.DriverManager.getConnection(this.url, props);

##方法二:连接url参数
直接将参数加到数据库连接url,如下代码中在数据连接url中添加了两个参数characterEncoding=utf8useInformationSchema=true

String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&&useInformationSchema=true"
this.pConnection = DriverManager.getConnection(this.url, this.username,this.password);

关于mysql 连接URL的语法参见:
《5.1 Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J》

#参考资料
《Connector/J does not retrieve the table comment in a InnoDB table》
《Retrieve mysql table comment using DatabaseMetaData》
《Chapter 24 INFORMATION_SCHEMA Tables》
《5.1 Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J》

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10km

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值