2

I want to insert a record in mytable (in DB2 database) and get the id generated in that insert. I'm trying to do that with python 2.7. Here is what I did:

import sqlalchemy
from sqlalchemy import *
import ibm_db_sa

db2 = sqlalchemy.create_engine('ibm_db_sa://user:pswd@localhost:50001/mydatabase')
sql = "select REPORT_ID from FINAL TABLE(insert into MY_TABLE values(DEFAULT,CURRENT TIMESTAMP,EMPTY_BLOB(),10,'success'));"
result = db2.execute(sql)
for item in result:
    id = item[0]
print id

When I execute the code above it gives me this output:

10 //or a increasing number

Now when I check in the database nothing has been inserted ! I tried to run the same SQL request on the command line and it worked just fine. Any clue why I can't insert it with python using sqlalchemy ?

3
  • 1
    Did you forget to commit? Commented Mar 11, 2015 at 15:07
  • @Lennart I don't think that commit is the problem because when I run a simple INSERT INTO with the same code it insert the record correctly. Commented Mar 11, 2015 at 15:14
  • should the ; be included in the query? Commented Mar 11, 2015 at 15:45

1 Answer 1

3

Did you try a commit? @Lennart is right. It might solve your problem.

Your code does not commit the changes you have made and thus are rolled back. If your Database is InnoDB, it is transactional and thus needs a commit.

according to this, you also have to connect to your engine. so in your instance it would look like:

db2 = sqlalchemy.create_engine('ibm_db_sa://user:pswd@localhost:50001/mydatabase')
conn = db2.connect()
trans = conn.begin()
try:
    sql = "select REPORT_ID from FINAL TABLE(insert into MY_TABLE values(DEFAULT,CURRENT TIMESTAMP,EMPTY_BLOB(),10,'success'));"
    result = conn.execute(sql)
    for item in result:
        id = item[0]
    print id
    trans.commit()
except:
    trans.rollback()
    raise

I do hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Out of curiosity, is trans.rollback() necessary? I would think that if you never commit(), it should rollback(), and I would think if your trans encountered an exception, you'd want to conn.end() or trans.end() or whatever the case might be? I'm not sure about any of the above though; trying to check my assumptions. Otherwise, though, this solved my issue. Not sure why other INSERT statements succeed without requiring a commit(), but that's for a different post, I guess. Anyways, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.