MySQLdb.cursors.Cursor.execute不执行

2024-04-25 13:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经做了以下工作:

import MySQLdb as mdb
con = mdb.connect(hostname, username, password, dbname)
cur = con.cursor()
count = cur.execute(query)
cur.close()
con.close()

我有两个查询,我在mysql控制台中执行它们,我可以查看结果。
但是,当我通过python提供相同的查询时,一个查询有效,另一个则无效。
我确信mysql、query或python代码没有问题。我怀疑cur.execute(query)函数。

有人经历过类似的情况吗?有什么解决办法吗?


Tags: importcloseexecuteasconnectmysqlusernamepassword
3条回答

This is a function and the query is passed to this function. When I execute one query after the other. I dont get the result for few queries, there is no problem with the queries because I have crossed checked them with the mysql console.

当你在评论中澄清你的问题时,我给出了另一个答案——完全不同的方法。

您是否以自动提交模式连接到数据库?如果没有,要永久应用更改,您必须^{}它们。在正常情况下,不应为每个请求创建新连接。这使得数据库服务器负载过重,几乎一无所获:

# Open a connection once
con = mdb.connect(hostname, username, password, dbname)


# Do that *for each query*:
cur = con.cursor()
try:
    count = cur.execute(query)
    conn.commit() # don't forget to commit the transaction
else:
    print "DONE:", query # for "debug" -- in real app you migth have an "except:" clause instead
finally:
    cur.close() # close anyway


# Do that *for each query*:
cur = con.cursor()
try:
    count = cur.execute(query)
    conn.commit() # don't forget to commit the transaction
else:
    print "DONE:", query # for "debug" -- in real app you migth have an "except:" clause instead
finally:
    cur.close() # close anyway


# Close *the* connection
con.close()

上面的代码直接输入到SO中。请原谅输入错误和其他基本语法错误。但这就是它的精神。

最后一句话,在打字的时候我想知道你是如何处理异常的?MySQLdb错误有可能在程序的某个上层被忽略吗?

I have two queries, I execute them in the mysql console I can view the results.

但我只看到一个查询:

import MySQLdb as mdb
con = mdb.connect(hostname, username, password, dbname)
cur = con.cursor()
count = cur.execute(query)
cur.close()
con.close()

我的猜测query包含由一个半冒号分隔的查询和INSERT语句吗?您可能需要使用executemany()

Executing several SQL queries with MySQLdb


另一方面,如果您的两个查询都是SELECT语句(您说“I请参阅结果”),则我不确定您是否只能从对execute()的一个调用中获取这两个结果。无论如何,我认为那是一种糟糕的风格。

执行后使用conn.commit()提交/完成基于插入和删除的更改。

相关问题 更多 >