无法插入数据java mysql

juzqafwq  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(327)

**结案。**此问题不可复制或由打字错误引起。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

22小时前关门了。
改进这个问题
我有一个问题,我不能插入数据到数据库我使用java和mysql

try {
        String query1 = "insert into Client(Codecli,Nom,Ville,Datenais,Solde,Password) values(?,?,?,?,?,?)";
        PreparedStatement statement = connection.prepareStatement(query1);
        statement.setString(1, num.getText());
        statement.setString(2, nomField.getText());
        statement.setString(3, villeField.getText());
        statement.setDate(4, null);
        statement.setDouble(5, 0.0);
        statement.setString(6, passwordField.getText());
        statement.executeUpdate(query1);
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

它显示了这个错误
java.sql.sqlexception:参数索引超出范围(2>参数数,即1)。

vbopmzt1

vbopmzt11#

// prepared statements must be closed, so use a try-with-resources (or a try / catch / finally) 
// connection should not be closed in the try block because throwing an exception will leave it open.
try (PreparedStatement statement = connection.prepareStatement(query1);connection) {
    statement.setString(1, num.getText());
    statement.setString(2, nomField.getText());
    statement.setString(3, villeField.getText());
    statement.setDate(4, null);
    statement.setDouble(5, 0.0);
    statement.setString(6, passwordField.getText());

    // no parameters in executeUpdate() (your original problem)
    int result = statement.executeQuery();
    // returns the number of rows affected --- so a 0 = didn't work

} catch (Exception ex) {
    ex.printStackTrace();
}

完整的免责声明-我没有测试这个代码,但我99%确定,如果你做这些更改,它会工作。

相关问题