在oracle / JDBC中对主键进行排序

时间:2013-06-19 13:29:57

标签: java oracle jdbc sequence

所以我有代码:

public void addUser( 
            String username, String password,
            String f_name, String l_name, String email) 
    {
        try 
        {
            //conn.setAutoCommit(false); 
            pstmnt = conn.prepareStatement("INSERT INTO users VALUES (?,?,?,?)");
            pstmnt.setString(1, "user_id_increment.nextval");
            pstmnt.setString(2, username);
            pstmnt.setString(3, password);
            pstmnt.setInt(4, 0);

            pstmnt.execute();

在OraclebI中有序列:

--Auto incrementing the user_id
CREATE SEQUENCE user_id_increment
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 20;

但是,我在eclipse中得到了例外:

Error: ORA-01722: invalid number

我认为调用序列name.nextval会给出序列中的下一个值,当插入任何其他整数时,setString会起作用。

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

尝试

pstmnt = conn.prepareStatement("INSERT INTO users VALUES (user_id_increment.nextval,?,?,?)");
        pstmnt.setString(1, username);
        pstmnt.setString(2, password);
        pstmnt.setInt(3, 0);

您必须在SQL语句中包含序列,而不是将其作为参数传递。

setString适用于其他整数的原因可能是因为jdbc驱动程序可以将它们强制转换为整数(并且它不能强制“user_id_increment.nextval”)