Java_jdbc 基础笔记之十五 数据库连接(取得数据库自动生成的主键)

public class testGetKeyValue {
    /**
     * 取得数据库自动生成的主键
     */

    @Test
    public void testGeneratedKeys() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs=null;
        try {
            conn = JDBCTools.getConnection();
            String sql = "INSERT INTO customers(name,email,birth) VALUES(?,?,?)";
            // 使用重载的prepareStatement方法来生产 PreparedStatement对象
            ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, "AAA");
            ps.setString(2, "[email protected]");
            ps.setDate(3, new Date(new java.util.Date().getTime()));
            ps.executeUpdate();
            rs=ps.getGeneratedKeys();//得到插入行的主键

            if(rs.next()){
                System.out.println(rs.getObject(1));
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCTools.close(rs, ps, conn);

        }

    }

}

转 : https://blog.csdn.net/YL1214012127/article/details/48374637

猜你喜欢

转载自www.cnblogs.com/fps2tao/p/12027428.html