尝试将新数据添加到其中一个表时出错

时间:2015-04-10 11:19:33

标签: java mysql database add

处理一个项目,我必须将新数据添加到不同的表中(我是新手)。我正在使用连接到mysql数据库的Netbeans。数据库工作正常,我直接执行它时查询工作。但是当我尝试通过我的javacode用新数据更新表时,它失败了。

代码:

ConnectionClass db = new ConnectionClass();
    try {
        db.ConnectToDb();
    } catch (SQLException ex) {
        Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
    }

      String sql = "insert into users values (3, 'Nicklas', 'niklas@alskart.se', 'nisun', 'heej', '1')";

       /* String laggTill = "insert into agent values ("+idb.getAutoIncrement("agent", "aid")+
            ", '"+tfNamn.getText()+"', '"+tfNr.getText()+"', '"+tfMail.getText()+"')";

      */

    try {
        db.myStmt.executeUpdate(sql);
    } catch (SQLException ex) {
        Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
    }

}        

生成异常:

apr 10, 2015 1:17:47 EM Project.AddUser btn_saveNewUserActionPerformed
ALLVARLIG: null
    java.sql.SQLException: No operations allowed after statement closed.
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872)
    at com.mysql.jdbc.StatementImpl.checkClosed(StatementImpl.java:445)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1554)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1549)
    at Project.AddUser.btn_saveNewUserActionPerformed(AddUser.java:159)

2 个答案:

答案 0 :(得分:0)

将数据记录插入数据库时​​的基本步骤是:

Connection connection //connect to db
PreparedStatement statement;
String query = "INSERT INTO...";
statement = connection.prepareStatement(query);  //prepareStement (or createStatement()) based on query
statement.executeUpdate();

我认为您错过了prepareStatement()或createStatement()步骤。

所以(我不知道您的ConnectionClass是什么样的,请发布它):

try {
        db.myStmt.createStatement();
        db.myStmt.executeUpdate(sql);
    } catch (SQLException ex) {
        Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
    }

最后,您必须关闭连接和声明。

工作示例:http://www.mkyong.com/jdbc/jdbc-statement-example-insert-a-record/

答案 1 :(得分:0)

嗨,请看你的堆栈跟踪 java.sql.SQLException:语句关闭后不允许任何操作。 表示Statement对象不存在。 你可以通过以下方式做到:

Statement myStmt;

try {
        myStmt = db.createStatement();
        myStmt.executeUpdate(sql);
    } catch (SQLException ex) {
        Logger.getLogger(AddUser.class.getName()).log(Level.SEVERE, null, ex);
    }

我假设引用变量db的类型为Connection。