简体   繁体   English

使用Java预准备语句将新记录添加到数据库

[英]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' 线程“ main”中的异常com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:键“ PRIMARY”的条目“ 939”重复

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

Connection conn = SimpleDataSource.getConnection(); 连接conn = SimpleDataSource.getConnection();

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; 线程“ main”中的异常com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL语法有错误。 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 检查与您的MySQL服务器版本对应的手册以获取正确的语法,以在第1行的'student_name ='mark'degree_Scheme ='cis'附近使用

        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. 这表明您正在插入一行或更新一行以使其具有表中已经存在的PRIMARY KEY值。 (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.) (组成PRIMARY KEY的列的值在每一行上必须是唯一的;任何两行都不能具有相同的值。)

This query: 该查询:

UPDATE student SET studentId = ?

Is going to attempt to set the studentId column to the same value on every row. 尝试将每一行的studentId列设置为相同的值。

We're guessing that studentId is defined as the PRIMARY KEY of the student table, and that the table contains more than one row. 我们猜测studentId被定义为student表的PRIMARY KEY,并且该表包含多个行。 We'd expect the execution of this statement to throw a "duplicate key" exception, like the one you are reporting. 我们希望该语句的执行会引发“重复键”异常,就像您要报告的异常一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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