user2297666
user2297666

Reputation: 321

Sequencing primary key in oracle / JDBC

So I have the code :

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();

And in OraclebI have the sequence :

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

However, I'm getting the exception in eclipse:

Error: ORA-01722: invalid number

I thought calling the sequence name.nextval will give me the next value in the sequence, the setString works when I plug in any other integer.

Any ideas?

Upvotes: 1

Views: 908

Answers (1)

DaveH
DaveH

Reputation: 7335

Try

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

You have to include your sequence in the SQL statement, rather than pass it as a parameter.

The reason setString works for the other integers is presumeably because the jdbc driver can coerce them into integers ( and it can't coerce "user_id_increment.nextval" )

Upvotes: 5

Related Questions