From Gossip@Openhome

Java Gossip: ResultSetMetaData 類別

Meta Data即「資料的資料」(Data about data),ResultSet用來表示查詢到的資料,而ResultSet資料的資料,即描述查詢到的資料背後的資料描述,即用來表示表格名稱、欄位名稱、欄位型態等等,這些訊息您可以透過ResultSetMetaData來取得。

下面這個範例直接示範如何取得查詢到的資料欄位數、表格名稱、欄位名稱與欄位資料型態:

  • ResultSetMetaDataDemo.java
package onlyfun.caterpillar;

import java.sql.*;

public class ResultSetMetaDataDemo {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/GUESTBOOK?" +
"useUnicode=true&characterEncoding=Big5";
String user = "caterpillar";
String password = "123456";

Connection conn = null;
Statement stmt = null;

try {
Class.forName(driver);
conn = DriverManager.getConnection(
url, user, password);

stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(
"SELECT * FROM message");
ResultSetMetaData metadata =
result.getMetaData();

for(int i = 1;
i <= metadata.getColumnCount();
i++) {

System.out.print(
metadata.getTableName(i) + ".");
System.out.print(
metadata.getColumnName(i) + "\t|\t");
System.out.println(
metadata.getColumnTypeName(i));
}
}
catch(ClassNotFoundException e) {
System.out.println("找不到驅動程式");
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
finally {
if(stmt != null) {
try {
stmt.close();
}
catch(SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
}
catch(SQLException e) {
e.printStackTrace();
}
}
}
}
}