List list = new ArrayList();
Class.forName("com.mysql.jdbc.Driver");
try {
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","root");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/read",properties);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from user where id = 5");
//获取数据库 列总数 和 列名
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int count = resultSetMetaData.getColumnCount();
while(resultSet.next())
{
Map columnList = new HashMap();
for(int i = 1 ; i<=count ; i ++ )
{
columnList.put(resultSetMetaData.getColumnName(i),resultSet.getObject(i));
}
list.add(columnList);
}
} catch (SQLException e) {
e.printStackTrace();
}
String l = JSON.toJSONString(list);
System.out.println(JSON.toJSONString(l));
网友评论