python - 如何在Python中执行多重查询?

标签 python mysql-python

我想执行下面函数中给出的 sql_query 并这样做:

def get_globalid(self): 
    cursor = self.connect()
    sql_query = "REPLACE INTO globalid (stub) VALUES ('a'); SELECT LAST_INSERT_ID() as id"
    cursor = self.query(sql_query, cursor)
    for row in cursor:
        actionid = row[0]
    return actionid

connect() 函数我用来建立连接,它是单独定义的。我上面使用的查询函数是执行传递给它的任何查询。它的定义为:

def query(self,query,cursor):
    cursor.execute(query)
    self.close()
    return cursor 

它无法正常工作。我有什么遗漏的吗? python 是否有像 php (multi_query) 中那样的 mysqli 函数?

最佳答案

mysql-python 无法执行分号分隔的多个查询语句。 如果您正在寻找last_insert_id,您可以尝试使用以下方法:

conmy = MySQLdb.connect(host, user, passwd, db)
cursor = conmy.cursor()
sql_query = "REPLACE INTO globalid (stub) VALUES ('a')"
cursor.execute(sql)
last_insert_id = conmy.insert_id()
conmy.close()

关于python - 如何在Python中执行多重查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20094456/

相关文章:

python - 我的 Mercurial Hook 是否可以从另一个文件调用代码?

python - 如何检测python-docx中的空段落

python - 使用 pip 和 easy_install 将 MySQL-python 安装到 virtualenv 时出现注册表错误

mysql - SQL 查询 - 第二大数字

Python MySQLdb,简单的聊天室/留言簿应用程序

Python MySQLdb/mysql 客户端 : bind a named set (or tuple or list) as parameter

Python:如何将所有 'for loop' 输出作为一个变量解析到 mysql 更新查询

python - 平均精度未正确显示(scikit)

python - Pandas - 重新采样/按日期时间索引进行分组并执行计算

python - Scrapy不抓取下一页url