jdbc mysql user_tab_comments_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,
DatabaseMetaDataUsingInfoSchema是DatabaseMetaData是的子類,看名稱就能聯想到是通過 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?
而父類DatabaseMetaData并不一定能正常返回table_comment字段.
解決方法
解決的方法也很簡單:
數據庫連接時設置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=utf8和useInformationSchema=true
String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&&useInformationSchema=true"
this.pConnection = DriverManager.getConnection(this.url, this.username,this.password);
參考資料
總結
以上是生活随笔為你收集整理的jdbc mysql user_tab_comments_mysql/jdbc:设置useInformationSchema=true读取表注释信息(table_comment)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 个人所得税申报方式怎么选
- 下一篇: mysql innodb表损坏_MySQ