Java连接数据库及简单操作见我以前的一篇随笔:http://www.cnblogs.com/meitian/p/5036332.html
一、获取查询结果的行数和列数
查询结果为ResultSet对象
ResultSet selectresult = this.executequery(sql_temp);
查看列数:
int column_count=selectresult.getMetaData().getColumnCount();
getMetaData()返回了所有列信息
getMetaData().getColumnName(i):i传递列int索引可获得列的名
查看行数:
int row_count=selectresult.getRow();
二、打印查询结果的列明和对应值
所以如果想打印查询出来的值,可以先查询查询结果列数,然后循环进行打印,代码如下
this.con = DriverManager.getConnection(url, user, password); this.stmt = con.createStatement(); ResultSet selectresult =this.stmt.executeQuery(sql); int column_count = selectresult.getMetaData().getColumnCount(); int size = 0; while (selectresult.next() && size < 10) { String selectresult_single = ""; for (int i = 1; i <= column_count; i++) { String ColumnName = selectresult.getMetaData().getColumnName(i); String ColumnValue = selectresult.getString(i); selectresult_single = selectresult_single + ColumnName + "=" + ColumnValue + " "; } size = size + 1; }
说明:因为不想打印所有结果,所以我这里在while里加了一个打印数量上限10
原文地址:https://www.cnblogs.com/meitian/p/9025810.html
时间: 2024-10-09 07:28:23