简体   繁体   中英

Adding a new record to a database with java prepared statements

I am creating a method to load in vales from an interface to create a new record in my database.

I have tried several methods and keep getting different errors.

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '939' for key 'PRIMARY'

    public boolean newStudent(String studentId, String name, String degreeScheme) throws SQLException 
{ 
    // Use SIMPLEDATASOURCE connection

Connection conn = SimpleDataSource.getConnection();

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'student_name = 'mark' degree_Scheme = 'cis'' at line 1

        try {
          conn.createStatement();
          PreparedStatement stat = conn.prepareStatement( "UPDATE student SET studentId = ?");
          stat.setString(1,studentId); // Use parameter 
          stat.executeUpdate(); // Execute prepared stat
         return stat.executeUpdate() == 1 ;

        }
    finally
    {
        // Close the connection
        conn.close();
    }
}

Was there a question in there somewhere?

Duplicate entry '939' for key 'PRIMARY'

This indicates that you are either inserting a row or updating a row to have a PRIMARY KEY value that already exists in the table. (The value of the column(s) making up the PRIMARY KEY must be UNIQUE on each row; no two rows can have the same value.)

This query:

UPDATE student SET studentId = ?

Is going to attempt to set the studentId column to the same value on every row.

We're guessing that studentId is defined as the PRIMARY KEY of the student table, and that the table contains more than one row. We'd expect the execution of this statement to throw a "duplicate key" exception, like the one you are reporting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM