我有一个返回不同类型数据的ResultSet。查询是动态构造的,因此在编译时,我不知道查询将返回什么类型的值。
我已经编写了以下代码,假设所有结果都是字符串。但我也希望得到每个值的类型。我怎么能这样做?
以下是我编写的代码。
while (reportTable_rst.next()) {
String column = reportTable_rst.getString(columnIterator);
}
此时,我想获取列类型,并根据数据类型获取值。
答案 0 :(得分:37)
ResultSetMetaData.getColumnType(int column)
返回int
值,指定java.sql.Types
中找到的列类型。
示例:
Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
PreparedStatement statement = connection.prepareStatement(JDBC_SELECT);
ResultSet rs = statement.executeQuery();
PrintStream out = System.out;
if (rs != null) {
while (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
if (i > 1) {
out.print(",");
}
int type = rsmd.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
out.print(rs.getString(i));
} else {
out.print(rs.getLong(i));
}
}
out.println();
}
}
答案 1 :(得分:3)
你可以打电话,
返回指定列的SQL类型。
int ResultSetMetaData.getColumnType(int column)
返回指定列的特定于数据库的类型名称。
String ResultSetMetaData.getColumnTypeName(int column)
答案 2 :(得分:3)
ResultSet rs;
int column;
.....
ResultSetMetaData metadata = rs.getMetaData();
metadata.getColumnTypeName(column); // database specific type name
metadata.getColumnType(column); // returns the SQL type
答案 3 :(得分:1)
我认为上面的答案并没有循环,而且缺乏细节。此代码段可以改进为只显示列名和相应的数据类型。这是完全有效的代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class Test {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String HOST = "192.168.56.101";
private static final String PORT = "3316";
private static final String CONNECTION_URL = "jdbc:mysql://"+HOST+":"+PORT+"/";
private static final String USERNAME = "user";
private static final String PASSWORD = "pwd";
private static final String DATABASE = "db";
private static final String TABLE = "table";
private static final String QUERY = "select * from "+DATABASE+"."+TABLE+" where 1=0";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName(DRIVER);
Connection con = DriverManager.getConnection (CONNECTION_URL , USERNAME, PASSWORD);
ResultSet rs = con.createStatement().executeQuery(QUERY);
if (rs != null) {
System.out.println("Column Type\t\t Column Name");
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.println(rsmd.getColumnTypeName(i)+"\t\t\t"+rsmd.getColumnName(i));
}
}
}
}