数据库连接jdbc

    技术2022-05-19  21

    在很多时候都会遇到和数据库的连接,当在向数据库的插入(PreparedStatement)有自动递增的字段时,可以调用PrepareStatement的一个方法prepareStatement(sql, Statement.RETURN_GENERATED_KEYS).下面是我做BBS时在发表新主题中的一段代码:

    String sql = "insert into article values (null,0,-1,?,?,now(),0)";  boolean autoCommit = conn.getAutoCommit();  conn.setAutoCommit(false);    PreparedStatement pstmt= conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);    pstmt.setString(1,title);  pstmt.setString(2,cont);  pstmt.executeUpdate();    ResultSet rsKey = pstmt.getGeneratedKeys();    //拿到自动生成的key  rsKey.next();  int id = rsKey.getInt(1);  rsKey.close();    stmt.executeUpdate("update article set rootid = " + id + " where id = " + id);    conn.commit();  conn.setAutoCommit(autoCommit);

     

    这些都是跟着马士兵老师学习的时候他讲的。


    最新回复(0)