2013-03-26 92 views
0

我的程序总是停止插入数据库表而不会崩溃。这里是我的代码用prepareStatement在java中插入数据库

创建数据源和连接:

public void setUp() throws Exception { 
    manager = new IngredientManager(); 
    BasicDataSource ds = new BasicDataSource(); 
    ds.setUrl("jdbc:derby:memory:ingredient;create=true");  
    manager.setDataSource(ds); 
    manager.createTables(); 
} 

方法createTables():

public void createTables() throws ServiceFailureException, SQLException { 
    Connection con = dataSource.getConnection(); 
    con.setAutoCommit(false); 
    String createTableSQL = "CREATE TABLE INGREDIENTS(" 
      + "ID BIGINT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, " 
      + "NAME VARCHAR(255), " 
      + "AMOUNT DOUBLE, " 
      + "UNIT VARCHAR(255), " 
      + "RECIPEID INTEGER NOT NULL " 
      + ")"; 

    PreparedStatement query = con.prepareStatement(createTableSQL); 
    query.executeUpdate(); 
} 

这一切工作正常,但是当程序涉及到这一点:

Connection connection = dataSource.getConnection(); 
connection.setAutoCommit(false); 
query = connection.prepareStatement("INSERT INTO INGREDIENTS (NAME, AMOUNT, UNIT, RECIPEID) VALUES(?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); 

在connection.prepareStatement程序没有做任何事情之后,只是永远建立。任何想法,为什么这可能会损坏?谢谢

+0

你是什么意思与_building forever_?你如何验证下面的代码永远不会被执行? – jlordo 2013-03-26 13:57:28

+0

我有方法query = connection.prepareStatement(..)上的断点和方法后的断点,程序将永远不会到达第二个断点 – 2013-03-26 13:59:50

+0

删除第一个断点。现在是否会接触到另一个? – jlordo 2013-03-26 14:00:48

回答

2

方法createTables()创建连接(和事务)到数据库。 挂起的代码创建第二个连接(和事务)。第二个事务被阻塞,直到第一个事务被提交,因为它们都锁定在同一个表上。

调用con.commit();createTables()的末尾应解决该问题。