Skip to main content
 首页 » 编程设计

python之如何在python中执行多查询

2024年11月01日10zfyouxi

我想执行下面函数中给出的 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  

它不能正常工作。有什么我想念的吗?是否有像 php (multi_query) 中那样的 python 的 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()