“preparedStatement.setString(1,msg);”的替代方案

时间:2014-04-08 08:34:10

标签: mysql prepared-statement

尝试将一些数据从用户表单插入MySQL。它包含一些简单的步骤。 从TextField读取值并将其插入表中。我的代码是:

public void enterStaff() throws ClassNotFoundException, SQLException {
try {
    Class.forName("com.mysql.jdbc.Driver");
    connect = DriverManager
            .getConnection("jdbc:mysql://localhost:3306/project?"
                    + "user=root&password=virus");
    statement = connect.createStatement();

    preparedStatement = connect
            .prepareStatement("SELECT count(*)FROM information_schema.tables\n"
                    + "WHERE table_schema = 'project' AND table_name = 'staff'");
    rs = preparedStatement.executeQuery();
    rs.next();
    int chk = rs.getInt(1);

    if (chk != 1) {
        preparedStatement = connect
                .prepareStatement("create table staff (staffname varchar(30) primary key);");
        preparedStatement.executeUpdate();
    }

    preparedStatement = connect
            .prepareStatement("insert into staff values(?);");
    preparedStatement.setString(1, addSubName.getText());

    preparedStatement.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
    throw e;
} finally {
    close2();
}

}

private void close2() {
try {

    if (statement != null) {
        statement.close();
    }

    if (connect != null) {
        connect.close();
    }
} catch (SQLException e) {

}
}

不幸的是,这段代码为密钥'PRIMARY'生成了“com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:Duplicate entry”。所以我编辑了我的代码,它是:

public void enterStaff() throws ClassNotFoundException, SQLException, 
        InstantiationException, IllegalAccessException {

    String sql;

    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connect = DriverManager
                .getConnection("jdbc:mysql://localhost:3306/project?"
                        + "user=root&password=virus");
        statement = connect.createStatement();

        sql = "SELECT count(*)FROM information_schema.tables "
                + "WHERE table_schema = 'project' AND table_name = 'staff'";

        rs = statement.executeQuery(sql);
        rs.next();
        int chk = rs.getInt(1);

        if (chk != 1) {
            sql="create table staff (staffname varchar(30) primary key)";
            rs = statement.executeQuery(sql);
        }

        sql="insert into staff values (?)";
        //preparedStatement.setString(1, msg); // ...HOW TO CHANGE IT ???

        rs = statement.executeQuery(sql);
    } catch (ClassNotFoundException | SQLException e) {
        throw e;
    } finally {
        close2();
    }

}

private void close2() {
    try {

        if (statement != null) {
            statement.close();
        }

        if (connect != null) {
            connect.close();
        }
    } catch (SQLException e) {

    }
}

我改变了大部分代码。但我不知道如何更改“preparedStatement.setString(1,addSubName.getText());”。如何根据新代码进行更改?

0 个答案:

没有答案