关于py-sqlite3报错:no such table:table name的问题解决

关于py-sqlite3报错:no such table:table name的问题解决

关于py-sqlite3报错:no such table:table name的问题解决_第1张图片
一.报错原因:

  • 没有创建表
  • 表存在,数据库存在,但是通过使用相对路径,可以在当前工作目录中打开它。如果sqlite使用相对路径引入数据库时,当使用打开文件对话框等给便当前路径的操作,就会导致问题的发生。
    二.解决方法:
    为数据库文件使用绝对路径。您可以基于脚本的绝对路径:
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, consts.database)

完整链接测试代码:

#!/usr/bin/python
import os
import sqlite3
import time

import consts

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, consts.database)

class SqliteHelper(object):
    def __init__(self, logger):
        self.logger = logger

    def connectDB(self):
        try:
            conn = sqlite3.connect(db_path)
        except Exception as e:
            time.sleep(1)
            conn = sqlite3.connect(db_path)
            self.logger.info("SqliteHelper.connectDB:{}".format(e))
        return conn

    def creat_table(self, table_name):
        res = False
        try:
            conn = self.connectDB()
            c = conn.cursor()
            sql = """CREATE TABLE {}
                   (name                VARCHAR(50)    NOT NULL,
                   floor                INT    NOT NULL,
                   phone_number         VARCHAR(50) NOT NULL,
                   camera_flag          INT    NOT NULL,
                   model_status         INT    NOT NULL,
                   create_time TimeStamp NOT NULL DEFAULT (datetime('now','localtime')),
                   update_time TimeStamp NOT NULL DEFAULT (datetime('now','localtime')),
                   primary key (phone_number,camera_flag))
                   """.format(table_name)
            c.execute(sql)
            conn.commit()
            conn.close()
            res = True
            self.logger.info("creat_table successfully!:{}".format(res))
        except Exception as e:
            self.logger.info("creat_table:{}".format(e))
        return res

你可能感兴趣的:(python-sqlite,数据库,其他)