Rohit Goel
Rohit Goel

Reputation: 3554

How to check whether query have inserted data or not in Python

I am using raw sql queries for inserting the data into DB. The insertion is working right, Now I want to perform some checks on this insert query e.g. If the query has inserted the data or not suppose I have insert query like

cursor.execute("some insert query" )

Now I want to know whether cursor.execute has inserted the row then show me some text like success and if it fails to insert for some reason then show me text like error and also if the row is already inserted then show, row already exist.

But I don't know how to perform these checks on cursor.execute.

edit

for i in range(numrows):
                row = cursor.fetchone()
                if row[6]==1:
                        arr["user_id"]=row[0]
                        arr["email"]=row[1]
                        arr["style_quiz_score"]=row[2]
                        arr["style_quiz_answer"]=row[3]
                        arr["date_joined"]=row[4]
                        arr["is_active"]=row[5]
                        arr['firstname'] = row[7]

                        arr["username"]=re.sub(r'[^a-zA-Z0-9]', '_', arr["email"])
                elif row[6]==2:
                        arr['lastname'] = row[7]
        cursor1.execute("insert into auth_user(id,username,first_name,last_name,email,password,is_staff,is_active,is_superuser,date_joined,last_login)  values(%s,%s,%s,%s,%s,'NULL',0,%s,0,%s,0)",[arr["user_id"],arr["username"],arr['firstname'],arr['lastname'],arr["email"],arr["is_active"],arr["date_joined"]])

when i am executing cursor1.execute outside forloop than it insert the last entry , but if i execute it in inside forloop than it gives error and nothing will be inserted

Upvotes: 1

Views: 2084

Answers (1)

Gonzalo
Gonzalo

Reputation: 4269

Assuming you're using Django (you're not specific about it in your question, but you're using the django tag), you need to do transaction.commit_unless_managed() (from django.db import transaction) after issuing the insert query with cursor.execute.

You can check for exceptions when calling commit_unless_managed to see if the insert went well or not:

from django.db import connection, transaction, DatabaseError, IntegrityError

cursor = connection.cursor()
cursor.execute("some insert query" )

try:
    transaction.commit_unless_managed()
except DatabaseError, IntegrityError:
    print 'error'
else:
    print 'success'

Upvotes: 2

Related Questions