我在连接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
函数中的连接,您还需要从该函数返回一个conn
之所以
conn
是None
,仅仅是因为db_connect
没有任何return
语句,所以return
值默认为None
。数据库连接看起来非常好,因为您没有收到错误消息在这种情况下,我建议使用一些面向对象编程而不是函数编程
相关问题 更多 >
编程相关推荐