繁体   English   中英

在一个查询中使用Python Mysql CREATE和INSERT

[英]Python Mysql CREATE and INSERT in one query

我正在使用Python连接到XAMPP中的MySQL。我正在创建一个字符串并将其通过队列传递给新进程。该字符串包含MySQL查询,该查询在执行时将创建一个表并插入到表中。以下是我的代码: -

from MySQLdb import connect
from os import _exit
from multiprocessing import Process,Queue
q=Queue()

def pkt():
    conn=connect(user='root',passwd='257911.',host='localhost',unix_socket="/opt/lampp/var/mysql/mysql.sock")
    cursor=conn.cursor()
    conn.select_db("try")
    while True:
        y=q.get()
        if y=="exit":
            break
        else:
            cursor.execute(y)
            conn.commit()
    cursor.close()
    conn.close()
    _exit(0)


if __name__=="__main__":
    a=Process(target=pkt)
    a.start()
    query="CREATE TABLE hello(id varchar(10) NOT NULL,name varchar(20)); INSERT INTO hello(id,name) VALUES('1234','sujata'); "
    q.put(query)
    q.put("exit")

执行代码后,出现以下错误:

Traceback (most recent call last):
  File "/usr/lib64/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib64/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "try.py", line 16, in pkt
    conn.commit()
ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

我在一个查询中插入多个表时遇到相同的错误。是否无法在一个语句中合并创建和插入? 谢谢。

不可以,您不能在同一行中给出多个用分号分隔的查询。 这是因为MySQLdb是周围的包装_mysql这使得它与Python的DB API接口(阅读更多有关API兼容这里 )。 该API通过PREPARE/EXECUTE语句工作,根据

文本必须表示单个语句,而不是多个语句。

我需要在执行后关闭游标。 这对我有用。

from MySQLdb import connect
from os import _exit
from multiprocessing import Process,Queue
q=Queue()

def pkt():
    conn=connect(user='root',host='localhost',unix_socket="/home/mysql/mysql/mysql.sock")
    cursor=conn.cursor()
    conn.select_db("try")
    while True:
        y=q.get()
        if y=="exit":
            break
        else:
            cursor.execute(y)
            cursor.close()
            conn.commit()
    conn.close()
    _exit(0)


if __name__=="__main__":
    a=Process(target=pkt)
    a.start()
    query="CREATE TABLE hello(id varchar(10) NOT NULL,name varchar(20)); INSERT INTO hello(id,name) VALUES('1234','sujata'); "
    q.put(query)
    q.put("exit")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM