使用PreparedStatement插入。如何自动递增ID?

时间:2013-07-03 01:18:21

标签: java mysql prepared-statement mysql-connector

我有一个PreparedStatement,例如:

 PreparedStatement preparedStatement = connect.prepareStatement("INSERT into employee (id, time, name" + "(?,?,?)",Statement.RETURN_GENERATED_KEYS);
 ResultSet tableKeys = preparedStatement.getGeneratedKeys();
 preparedStatement.executeUpdate();
 tableKeys.next();
 int autoGeneratedID = tableKeys.getInt(1);
 preparedStatement.setInt(1,autoGeneratedID);
 preparedStatement.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));                           
 preparedStatement.setString(3, "Test");
 preparedStatement.executeUpdate();

如您所见,Employee表具有自动递增的ID。我需要基本上使用preparedStatement自动添加它。谁能告诉我哪里出错了并纠正我?现在它只是给了我一个与Statement相关的错误。

3 个答案:

答案 0 :(得分:29)

将列完全从INSERT语句中删除。它将由数据库引擎生成。您的查询应该是:

INSERT INTO employee (time, name)
VALUES (?, ?)

其次,您必须先执行插入,然后从结果中获取密钥。

我相信你的代码应该是:

PreparedStatement preparedStatement = 
    connect.prepareStatement("INSERT into employee (time, name) VALUES (?,?)", 
    Statement.RETURN_GENERATED_KEYS);

preparedStatement.setTimestamp(1, 
    new java.sql.Timestamp(new java.util.Date().getTime()));                           
preparedStatement.setString(2, "Test");

preparedStatement.executeUpdate();

ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);

注意,此示例不检查已执行语句的成功或返回键的存在。

答案 1 :(得分:0)

    try{
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");

        PreparedStatement ps = con.prepareStatement("insert into imgslider(id,cmnt,date1,img,status) values(seq.nextval,?,?,?,?)");
        ResultSet rs = null;

        String s1 = "I’ve Come and I’m Gone: A Tribute to Istanbul’s Street";
        ps.setString(1,s1);

        Calendar calendar = Calendar.getInstance();
        java.sql.Date dd = new java.sql.Date(calendar.getTime().getTime());
        ps.setDate(2,dd);

        FileInputStream f1 = new FileInputStream("F:\\java\\slide-9.jpg");
        ps.setBinaryStream(3,f1,f1.available());

        ps.setInt(4,0);

        int i = ps.executeUpdate();
        System.out.println(i+" rows affected");

        con.close();
    }

这是我的PreparedStatement表格中的自动增量列代码。

答案 2 :(得分:0)

您应该对准备好的语句字符串进行一些修改(定义{{​​1}}语句),

default

该修改是由于发生此问题:Column count doesn't match value count at row 1 JAVA mysql

之后,您的代码如下所示:

"INSERT into employee VALUES(default,?,?)"

感谢Ic.的回答。