java中jdbc,利用反射查询数据
public static List<Map<String, Object>> queryForList() {
Connection connection = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Map<String, Object>> resultList = new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
String user = "root";
String password = "123456";
connection = DriverManager.getConnection(url, user, password);
String sql = "SELECT * FROM `user` WHERE id= ?";
stmt = connection.prepareStatement(sql);
stmt.setInt(1, 7);
rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int num = rsmd.getColumnCount();
Map<String, Object> map = new HashMap<>();
while (rs.next()) {
for (int i = 0; i < num; i++) {
String columnName = rsmd.getColumnName(i + 1);
map.put(columnName, rs.getString(columnName));
}
resultList.add(map);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return resultList;
}
数据表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(4) NOT NULL AUTO_INCREMENT COMMENT 'id主键',
`name` varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '姓名',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`sex` int(2) NOT NULL DEFAULT 0 COMMENT '性别:0女,1男',
`birth` datetime(0) NOT NULL COMMENT '生日',
`update_date` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新日期',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 300 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
|