ResultSetMetaData metaData = rs.getMetaData();
jdbc中有一步是返回结果集,在结果集中有个getMetaData()的方法就可以得到数据库中的所有值,例如字段名、行数、列数等等可以用debug看看
以下是jdbc的增删改 和 查的封装类,不用写bean类就可直接使用
package com.hp.factory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AllFactory {
final static String url = "jdbc:mysql://localhost:3306/project01?unicode=true&characterEncoding=UTF-8";
final static String user = "root";
final static String password = "root";
final static String driver = "com.mysql.jdbc.Driver";
public static Connection getConn()throws Exception {
Class.forName(driver);
return DriverManager.getConnection(url, user, password);
}
public static List<Map<String, Object>> executeQuery(String sql)throws Exception {
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
Connection conn = getConn();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
ResultSetMetaData metaData = rs.getMetaData();
Map<String, Object> map = new HashMap<String, Object>();
for(int i=1;i<=metaData.getColumnCount();i++) {
map.put(metaData.getColumnLabel(i), rs.getObject(i));
}
list.add(map);
}
rs.close();
ps.close();
conn.close();
return list;
}
public static int excuteUpdate(String sql) throws Exception {
Connection conn = getConn();
PreparedStatement ps = conn.prepareStatement(sql);
int i = ps.executeUpdate();
ps.close();
conn.close();
return i;
}
}
转载:https://www.cnblogs.com/lihui123/p/13842863.html