Java .nextval JDBC 插入问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4496336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 18:02:44  来源:igfitidea点击:

.nextval JDBC insert problem

javasqloraclejdbcora-01722

提问by jasonfungsing

I try to insert into table with sequence .nextval as primary key, the sql in Java is

我尝试以序列 .nextval 作为主键插入到表中,Java 中的 sql 是

sql = "INSERT INTO USER 
         (USER_PK, ACCOUNTNUMBER, FIRSTNAME, LASTNAME, EMAIL ) 
       VALUES 
         (?,?,?,?,?)";
   ps = conn.prepareStatement(sql);
   ps.setString(1, "User.nextval");
   ps.setString(2, accountNumber);
   ps.setString(3, firstName);
   ps.setString(4, lastName);
   ps.setString(5, email);

However, the error is ORA-01722: invalid number

但是,错误是 ORA-01722: invalid number

All the other fields are correct, I think it is the problem of sequence, is this correct?

其他字段都对,我觉得是顺序的问题,对吗?

采纳答案by OMG Ponies

The problem is that the first column is a numeric data type, but your prepared statement is submitting a string/VARCHAR data type. The statement is run as-is, there's no opportunity for Oracle to convert your use of nextval to get the sequence value.

问题是第一列是数字数据类型,但您准备好的语句提交的是字符串/VARCHAR 数据类型。该语句按原样运行,Oracle 没有机会转换您对 nextval 的使用来获取序列值。

Here's an alternative via Java's PreparedStatement syntax:

这是通过 Java 的 PreparedStatement 语法的替代方法:

sql = "INSERT INTO USER 
        (USER_PK, ACCOUNTNUMBER, FIRSTNAME, LASTNAME, EMAIL ) 
       VALUES 
        (user.nextval, ?, ?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, accountNumber);
ps.setString(2, firstName);
ps.setString(3, lastName);
ps.setString(4, email);

This assumes that useris an existing sequence -- change to suit.

这假定这user是一个现有的序列 - 更改以适应。