Reputation: 20896
Im trying to execute a insert statement that has a sequence number column but unable to determine the returning value.
When I execute the below statement without binding seqvalue I get a error. When I initialize the seqvalue to 0 and bind it the output is 0.
code
col2 = 'test'
qry=insert into table1 (col1,col2) value (seq1.nextval,:col2) returning col1 into :seqvalue
cur.excute(qry,:col2)
Please provide your inputs.
Upvotes: 2
Views: 4226
Reputation: 1
Create a sequence in database: Create sequence my_seq minvalue 1 maxvalue 99999999999999 increment by 1 start with 1 nocache noorder nocycle;
Create a Oracle function to generate sequence numbers in database: Create or replace function gen_seq Return number Is Seq_value number; Begin
Select my_seq.nextval into seq_value from dual;
Return seq_value;
End;
self.emp_id = cur.callfunc('gen_seq', int)
Use self.emp_id as bind variable in order to insert into your database.
Any doubt. Please feel free to ask.
Upvotes: 0
Reputation: 1510
You can try using the bind variable and prepare statements which would use the same oracle method as SEQ.nextval. Steps :
Make a DB connection using cx_Oracle.
Obtain a cursor from DB connection.
Declare variables : which will be pushed into Oracle insert statement. for example below:
var_CHANGES = 'Test Changes' var_COMMENTS = 'Test'
statement = "INSERT" + "\n" + \
"INTO CHANGE_LOG" + "\n" + \
"( CHANGE_LOG_ID" + "\n" + \
", CHANGE_TYPE" + "\n" + \
", CHANGE_DATE" + "\n" + \
", COMMENTS )" + "\n" + \
"VALUES" + "\n" + \
"( CHANGE_LOG_SEQ.nextval" + "\n" + \
", :bCHANGE_TYPE" + "\n" + \
", sysdate" + "\n" + \
", :bCOMMENTS )"
then, using regex substitution format the query :
stmt = re.sub('\s+',' ',stmt.replace('\n',' ').replace('\r',''))
cursor.execute(statement, bCHANGE_TYPE=var_CHANGES \
, bCOMMENTS = var_COMMENTS )
So, here you can use SQL nextval() and sysdate as in the normal SQL query. This should do the job for you.
Upvotes: 1