为什么我无法连接到数据库

时间:2018-12-04 10:29:55

标签: python-3.x class sqlite

import lot_details, car_details
import numpy as np
import sqlite3

conn = sqlite3.connect('parkingLot.db')
c = conn.cursor()

class Parking(object):


    """
    Parking class which has details about parking slots
    as well as operation performed on parking are present here
    """

    def __init__(self):
        self.slots = {}

    def create_parking_lot(self, no_of_slots):

        try:
            c.execute('CREATE TABLE IF NOT EXISTS parkingTable(slot_no REAL, reg_no TEXT, colour TEXT, total_time TEXT,charge TEXT)')
        except Exception as ex:
            print("Couldn't make a table in DB")
        no_of_slots = int(no_of_slots)

        if len(self.slots) > 0:
            print ("Parking Lot already created")
            return

        if no_of_slots > 0:
            for i in range(1, no_of_slots+1):
                temp_slot = lot_details.PSlot(slot_no=i, available=True)
                self.slots[i] = temp_slot
            print ("Created a parking lot with {} slots" .format(no_of_slots))
        else:
            print ("Number of slots provided is incorrect.")
        return

使用上述代码,我试图创建一个数据库(成功),但是现在我无法使用上述命令在其中创建表。 我尝试单独进行操作。但是,我无法使用上面的代码创建它。

1 个答案:

答案 0 :(得分:0)

根据您创建Parking对象的方式和位置,我怀疑这可能是范围问题,可以将db连接传递到构造函数中,也可以只在构造函数本身中创建它。为简洁起见,修改了代码。以下对我有用。

import sqlite3

class Parking(object):

    def __init__(self):
        self.slots = {}
        self.conn = sqlite3.connect('parkingLot.db')

    def create_parking_lot(self, no_of_slots):

        try:
            cur = self.conn.cursor()
            cur.execute('CREATE TABLE IF NOT EXISTS parkingTable(slot_no REAL, reg_no TEXT, colour TEXT, total_time TEXT,charge TEXT)')
        except Exception as ex:
            print("Couldn't make a table in DB")

        return

parking = Parking()
parking.create_parking_lot(5)