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

来源:互联网 发布:debian ubuntu 对比 编辑:程序博客网 时间:2024/05/16 11:06
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, "aaa@sina.com");            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);        }    }}
0 0
原创粉丝点击