如何判断cursor.execute()执行的查询是否正确?

1 投票
1 回答
2259 浏览
提问于 2025-04-17 08:53
query = "delete from mytable where id =10"
cursor = connection.cursor()
cursor.execute(query)

它返回的是None,但我想知道查询的结果。我该怎么才能得到结果呢?

插入语句也是一样。有没有人能给我个解决办法?

1 个回答

1

我快速看了一下文档:

Django / 数据库文档: https://docs.djangoproject.com/en/dev/topics/db/sql/

在Django中,django.db.connection代表默认的数据库连接,而django.db.transaction代表默认的数据库事务。要使用数据库连接,首先调用connection.cursor()来获取一个游标对象。接着,使用cursor.execute(sql, [params])来执行SQL语句,然后可以用cursor.fetchone()或cursor.fetchall()来获取结果行。

还有Mysql / Python文档: http://www.tutorialspoint.com/python/python_database_access.htm

在执行查询后要提交:

# Prepare SQL query to DELETE required records
sql = "delete from mytable where id =10"
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

希望这些对你有帮助。

撰写回答