光标返回错误。
main.py:
def initialize_database():
conn = sqlite3.connect('PostsData.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
link TEXT NOT NULL,
username_id INTEGER,
FOREIGN KEY (username_id) REFERENCES users (id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
alias TEXT,
profile_picture TEXT
)
''')
conn.commit()
conn.close()
initialize_database()
控制台:
Traceback (most recent call last):
File "C:\Users\1222\Desktop\pathtoproj\main.py", line 38, in <module>
initialize_database()
File "C:\Users\1222\Desktop\pathtoproj\main.py", line 15, in initialize_database
cursor.execute('''
sqlite3.DatabaseError: malformed database schema (posts) - incomplete input
首先这有效。当将其连接到服务器上的数据库失败时,我决定返回到此选项,但这一次出现了问题。
由于
posts.username_id
是引用 users.id
的外键,因此需要在 users
表之前创建 posts
表,以便所述外键能够进行该引用。
因此交换表创建的顺序:
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
alias TEXT,
profile_picture TEXT
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL,
link TEXT NOT NULL,
username_id INTEGER,
FOREIGN KEY (username_id) REFERENCES users (id)
)
''')