1

我正在使用原始 sql 查询将数据插入数据库。插入工作正常,现在我想对这个插入查询执行一些检查,例如,如果查询插入了数据,或者假设我没有插入查询,比如

cursor.execute("some insert query" )

现在我想知道是否 cursor.execute已插入该行,然后显示一些文本,如成功,如果由于某种原因无法插入,则显示文本,如错误,如果该行已插入,则显示,行已存在

但我不知道如何对cursor.execute.

编辑

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"]])

当我 cursor1.execute在forloop外部执行时,它会插入最后一个条目,但是如果我在forloop内部执行它,则会出错并且不会插入任何内容

4

1 回答 1

2

transaction.commit_unless_managed()假设您使用的是 Django (您在问题中没有具体说明它,但您使用的是 django 标签),您需要在from django.db import transaction使用cursor.execute.

您可以在调用时检查异常commit_unless_managed以查看插入是否顺利:

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'
于 2013-02-07T10:53:14.410 回答