如何通过属性名称从ResultSet获取值?
数据库表(表格):
name:TEXT | age:INT | gender:INT
SQL查询:
SELECT * FROM table WHERE name='john'
输出位于java.sql.ResultSet
如何按列的名称(姓名,年龄,性别)获取变量?
答案 0 :(得分:2)
ResultSetMetaData metaData = resultSet.getMetaData();
例如:
...
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int count = metaData.getColumnCount();
for (int i = 1; i <= count; i++)
{
String columnName = metaData.getColumnName(i);
int type = metaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
out.print(rs.getString(columnName));
String name= rs.getString(columnName);
}
if (type==Types.INTEGER){
out.print(rs.getInt(columnName));
int age= rs.getInt(columnName);
}
// ....
// save columnName and name
}
}
}
...
答案 1 :(得分:1)
你可以对这些值进行迭代:
Statement stmt = null;
String query = "SELECT * FROM table WHERE name='john'";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name= rs.getString("name");
int age= rs.getInt("age");
int gender = rs.getInt("gender");
}
} catch (Exception e ) {
e.printStackTrace();
} finally {
if (stmt != null) { stmt.close(); }
}