使用sqlite3时出现python多处理错误

2024-04-18 04:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

在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()

当我在__init__中初始化self.conn时,它在__get_people中不起作用。错误消息是:

cur.execute('SELECT * FROM people')
OperationalError: no such table: people

我不知道是什么引起的。当我像注释一样直接使用原始连接时,效果很好。谢谢。你知道吗


Tags: textnameimportselfidgetinitdef
1条回答
网友
1楼 · 发布于 2024-04-18 04:25:50

您的问题似乎是忘记实际执行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的方式可能有问题,如果是这样的话,请纠正我,如果我在此之前没有完成。但这会让你知道怎么了。你知道吗

相关问题 更多 >