日期:2014-05-19 浏览次数:20741 次
Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager .getConnection("jdbc:mysql://localhost/BBS?user=root&password=root"); //连接数据库 conn.setAutoCommit(false); //不自动提交 String sql = "insert into article values (null,0,?,?,?,now(),0)"; PreparedStatement pstat = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); //创建一个默认 PreparedStatement 对象,该对象能获取自动生成的键,适合insert语句 //(该语句能自动生成键值)autoGeneratedKeys - 指示是否应该返回自动生成的键的标志 Statement stat = conn.createStatement(); pstat.setInt(1, -1); pstat.setString(2,title); pstat.setString(3,content); pstat.executeUpdate(); ResultSet rsKey = pstat.getGeneratedKeys(); //ResultSet 指示键值 rsKey.next(); int key = rsKey.getInt(1); //得到第一个键值 stat.executeUpdate("update article set rootid = " + key + " where id = " + key); conn.commit(); conn.setAutoCommit(true); //设回自动提交