19

我有一个 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 相关的错误。

4

3 回答 3

35

将该列完全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);

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

于 2013-07-03T01:20:33.650 回答
2

default您应该对准备好的语句字符串执行一些修改(定义语句),如下所示:

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

该修改是因为发生了这个问题:Column count doesn't match value count at row 1 JAVA mysql

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

PreparedStatement preparedStatement = 
connect.prepareStatement("INSERT into employee VALUES (default,?,?)", 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();

感谢IC。为他的回答。

于 2019-03-09T14:34:34.147 回答
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 表中自动增量列的代码。

于 2018-05-31T07:42:16.687 回答