打印结果集中的数据以及列名

2022-08-31 17:47:34

我正在通过Java从SQL数据库中检索列名。我知道我也可以从中检索列名。所以我有这个sql查询ResultSet

 select column_name from information_schema.columns where table_name='suppliers'

问题是我不知道如何从中获取列名,我的代码是ResultSet

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


}

答案 1
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("");
}

参考 :打印结果集的结果


答案 2

1) 不使用PreparedStatementStatement

2) 在 中执行查询后,在 以下的帮助下提取值:ResultSetrs.getString()

Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
    rs.getString(1); //or rs.getString("column name");
}

推荐