JDBC 事务开始(sqlserver2008)
1.插入主表一条语句
2.查询主表新插入一条语句的主键(Connection 未提交如何查询到?)
3.插入从表一条语句(connection 未提交如何获得外键值?)
     事务结束如何解决?先谢谢~!

解决方案 »

  1.   

    如果使用jdbc,就自动有事务提交了。
      

  2.   

    JDBC 事务开始(sqlserver2008)
    Connection.setAutoCommit(false)
    1.插入主表一条语句
    2.查询主表新插入一条语句的主键(Connection 未提交如何查询到?)
    3.插入从表一条语句(connection 未提交如何获得外键值?)
      事务结束
      

  3.   

    你主表的主键是如何生成的?如果是用@@IDENTITY那么执行SELECT @@IDENTITY应该能够获取的到,如果你是自己的方式生成的话,那么你可以先获取到ID,然后再写入insert语句中。
      

  4.   


    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);     //设回自动提交 
    如果表的主键是自增IDENTITY,可以使用MSSQL的内置函数SCOPE_IDENTITY(),我以前就采用了这种方法,比较简洁,但移植性差。
      

  5.   

    不用提交事务就可以拿到主表或从表的主键了,执行了SAVE方法,就有方法拿到了,事务没提交,可以代表实体的值没保存到硬盘中,但这时实体的值已经在内存中生成了。