2017-02-20 103 views
0

我需要帮助,我试图插入一些东西到现有的数据库中,但我无法完成。我得到数据库文件被锁定(数据库被锁定)。我试过关闭preparedStatement,但没有运气。我使用executeUpdate()而不是executeQuery(),没有帮助。SQLite正忙,数据库被锁定

public class tableController { 
Connection connection; 

@FXML 
private TextField txtId; 

@FXML 
private TextField txtName; 

@FXML 
private TextField txtLastName; 

@FXML 
private TextField txtAge; 

@FXML 
private TextField txtUsername; 

@FXML 
private TextField txtPassword; 

@FXML 
private Button save; 


public tableController() { 
    connection = SQLiteConnection.connector(); 
    if(connection == null) { 
     System.out.println("Test"); 
     System.exit(1); 
    } 
} 

public boolean isDBConnected() { 
    try { 
     return !connection.isClosed(); 
    } catch (SQLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return false; 
    } 
} 

public void Insert(ActionEvent event) throws SQLException { 

    PreparedStatement preparedStatement = null; 
    ResultSet resultSet; 
    String query = "insert into employee (id, name, lastName, age, username, password) values (?,?,?,?,?,?)"; 

    try { 
     preparedStatement = connection.prepareStatement(query); 
     preparedStatement.setString(1, txtId.getText()); 
     preparedStatement.setString(2, txtName.getText()); 
     preparedStatement.setString(3, txtLastName.getText()); 
     preparedStatement.setString(4, txtAge.getText()); 
     preparedStatement.setString(5, txtUsername.getText()); 
     preparedStatement.setString(6, txtPassword.getText()); 

     Alert aleret = new Alert(AlertType.INFORMATION); 
     aleret.setTitle("Information dialog"); 
     aleret.setHeaderText(null); 
     aleret.setContentText("User has been created"); 
     aleret.showAndWait(); 


     preparedStatement.executeUpdate(); 


    } catch (Exception e) { 
     // TODO: handle exception 
     JOptionPane.showMessageDialog(null, e); 
     e.printStackTrace(); 
    } finally { 
     if(preparedStatement != null) { 
      preparedStatement.close(); 
     } 
    } 
} 

}

+1

其他一些连接(在这个或另一个程序中)有一个活动事务。 –

+0

@CL。所有其他项目都关闭,后台没有任何内容正在运行。我该如何解决这个问题? – szentmihaly

+0

尝试复制.db文件,然后将该副本用于您的程序,并查看会发生什么 –

回答

0

我已经找到了解决办法。 @CL。是对的,有其他连接对象在后台运行。 问题在于,当登录到应用程序时,我没有关闭preparedStatement和resultSet。

PreparedStatement preparedStatement; 
    ResultSet resultSet; 
    String query = "select * from employee where username = ? and password = ?"; 

    try { 
     preparedStatement = connection.prepareStatement(query); 
     preparedStatement.setString(1, user); 
     preparedStatement.setString(2, pass); 

     resultSet = preparedStatement.executeQuery(); 


     if (resultSet.next()) { 
      preparedStatement.close(); // after closing this, it works 
      resultSet.close();   // closed this one also 
      return true; 
     } else { 
      return false; 
     } 


    } catch (Exception e) { 
     // TODO: handle exception 
     return false; 
    }