我在sqlite3中使用多进程时遇到问题。代码:
import multiprocessing
import sqlite3
class DealProcess(multiprocessing.Process):
def __init__(self):
super(DealProcess, self).__init__()
'''
CREATE TABLE people (id text, name text)
INSERT INTO people (id, name) VALUES ('1', 'jack')
'''
self.conn = sqlite3.connect('people.sqlite')
def __get_people(self):
cur = self.conn.cursor() # This not work, the following is OK,Why?
# conn = sqlite3.connect('people.sqlite')
# cur = conn.cursor()
cur.execute('SELECT * FROM people')
return cur.fetchall()
def run(self):
for people in self.__get_people():
print people
if __name__ == '__main__':
p = DealProcess()
p.start()
当我在self.conn
中初始化__init__
时,它在__get_people
中无效。错误消息是:
cur.execute('SELECT * FROM people')
OperationalError: no such table: people
我不知道是什么造成的。当我像注释一样直接使用原始连接时,它运行良好。感谢。
答案 0 :(得分:0)
您的问题似乎是您忘记了实际执行CREATE TABLE...
,因为它只是__init__
功能顶部的Multi line comment。
尝试在创建self.conn
后移动它并在其上运行cursor().execute
。
import multiprocessing
import sqlite3
class DealProcess(multiprocessing.Process):
def __init__(self):
super(DealProcess, self).__init__()
self.conn = sqlite3.connect('people.sqlite')
self.conn.cursor().execute('''
CREATE TABLE people (id text, name text)
INSERT INTO people (id, name) VALUES ('1', 'jack')
''')
def __get_people(self):
cur = self.conn.cursor() # This not work, the following is OK,Why?
# conn = sqlite3.connect('people.sqlite')
# cur = conn.cursor()
cur.execute('SELECT * FROM people')
return cur.fetchall()
def run(self):
for people in self.__get_people():
print people
if __name__ == '__main__':
p = DealProcess()
p.start()
在高速列车上,笔记本电脑上没有Python,因此语法可能会关闭
或者我使用函数.execute
的方式可能有一个小故障,如果是这样,如果我在此之前没有回家,请纠正我。但是这可以让你知道出了什么问题。