本文介绍了打印ResultSet中的数据以及列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过Java从SQL数据库中检索列名.我知道我也可以从ResultSet
检索列名.所以我有这个SQL查询
I am retrieving columns names from a SQL database through Java. I know I can retrieve columns names from ResultSet
too. So I have this sql query
select column_name from information_schema.columns where table_name='suppliers'
问题是我不知道如何从ResultSet
获取列名,而我的代码是
The problem is I don't know how can I get columns names from ResultSet
and my code is
public void getAllColumnNames() throws Exception{
String sql = "SELECT column_name from information_schema.columns where table_name='suppliers'";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
// extract values from rs
}
推荐答案
ResultSet resultSet = statement.executeQuery("SELECT * from foo");
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (resultSet.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(", ");
String columnValue = resultSet.getString(i);
System.out.print(columnValue + " " + rsmd.getColumnName(i));
}
System.out.println("");
}
参考: 打印ResultSet的结果
这篇关于打印ResultSet中的数据以及列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!