[英]Error! cannot create the database connection. / OS X / sqlite3 / python3
我在連接到我在 python 腳本過程中創建的 sqlite3 數據庫時遇到了一些問題。 它與腳本位於同一目錄中,並且正在創建,但表沒有被創建,因為它正在拋出:
Error! cannot create the database connection.
...執行時。
也許我錯過了一些愚蠢的東西,我不太喜歡 Python,但如果有人發現一些明顯的東西,這里是相關的來源:
import sqlite3
from sqlite3 import Error
def db_connect(fDB):
conn = None
try:
conn = sqlite3.connect(fDB)
print(sqlite3.version)
except Error as e:
print(e)
finally:
if conn:
conn.close()
def db_create_table(conn, create_table_sql):
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def db():
fDB = r"./fDB.db"
sql_create_fits_table = """ CREATE TABLE IF NOT EXISTS fits (
fHash text PRIMARY KEY,
fType text NOT NULL,
fFocus text NOT NULL,
fSurvey text NOT NULL,
fStart integer NOT NULL,
fEnd integer NOT NULL,
fDuration integer NOT NULL
); """
# create a database connection
conn = db_connect(fDB)
# create tables
if conn is not None:
# create fits table
db_create_table(conn, sql_create_fits_table)
else:
print("Error! cannot create the database connection.")
if __name__ == '__main__': # run db operations
db()
謝謝!
不要關閉db_connect
function 中的連接,您還需要從此 function 返回一個conn
。
def db_connect(fDB):
conn = None
try:
conn = sqlite3.connect(fDB)
print(sqlite3.version)
except Error as e:
print(e)
return conn
conn
為None
的原因僅僅是因為db_connect
沒有任何return
語句,因此return
值默認為None
。 數據庫連接看起來非常好,因為您沒有收到錯誤消息。
在這種情況下,我建議使用一些面向 object 的編程而不是函數式編程。
import sqlite3
class DBConnection:
def __init__(self, dbpath):
self.connection = sqlite3.connect(dbpath)
self.cursor = self.connection.cursor()
def create_table(self, query):
self.cursor.execute(query)
def main():
dbpath = f"./fDB.db"
sql_create_fits_table = """
CREATE TABLE IF NOT EXISTS fits (
fHash text PRIMARY KEY,
fType text NOT NULL,
fFocus text NOT NULL,
fSurvey text NOT NULL,
fStart integer NOT NULL,
fEnd integer NOT NULL,
fDuration integer NOT NULL
); """
connection = DBConnection(dbpath)
connection.create_table(sql_create_fits_table)
if __name__ == '__main__':
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.