- //使用元数据+反射优化CURD操作
- public class Demo2 {
-
- public static void main(String[] args) throws SQLException {
-
- String sql = "insert into user(username,password,birthday,salary) values(?,?,?,?)";
- Object[] params = {"xixi","00","1999-11-23",9000};
- update(sql,params);
- }
-
- public static void update(String sql,Object[] params) throws SQLException{
- Connection conn = JdbcUtil.getMySqlConnection();
- PreparedStatement pstmt = conn.prepareStatement(sql);
- //取得参数元数据
- ParameterMetaData pmd = pstmt.getParameterMetaData();
- //取得参数个数
- int size = pmd.getParameterCount();
- System.out.println(size);
- //为什么打印的是4,id那列它不读的吗?这又是为什么呢?
- for(int i=0;i<size;i++){
- pstmt.setObject(i+1, params[i]);
- System.out.println(params[i]);
- }
- pstmt.executeUpdate();
- }
- }
复制代码 id那列有的,虽然是自动增长,但是int size = pmd.getParameterCount();读取不到那列! |