2015-06-17 91 views
1

我正在使用Python來連接到MySQL的XAMPP.I創建一個字符串,並通過隊列將它傳遞給一個新的進程。字符串包含MySQL查詢,執行時會創建一個表並插入table.following是我的代碼: -Python 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") 

我正在上插入多個表了同樣的錯誤在一個查詢中。不可能將創建和插入組合在一起聲明? 謝謝。

回答

0

我需要執行之後關閉遊標。這對我有用。

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") 
1

不,你不能在同一行提供多個以分號分隔的查詢。這是因爲MySQLdb是一個圍繞_mysql的包裝,它使它與Python DB API接口兼容(請閱讀有關API here的更多信息)。該API通過PREPARE/EXECUTE報表工作,並根據this

The text must represent a single statement, not multiple statements.

+0

@sujata是否回答了您的問題? – sgp