我是Flask初学者,我想使用flask和sqlite3作为数据库引擎构建一个民意调查应用程序。
我的问题是如何创建两个表格,“问题”和“选择”,以便每个问题都有一些选择(可能不是固定数字。
我的原始方法相当幼稚:
drop table if exists entries;
create table question (
ques_id integer primary key autoincrement,
ques string not null,
choice1 string not null,
choice2 string not null,
choice3 string not null,
choice4 string not null,
pub_date integer
);
答案 0 :(得分:1)
以下是更normalized方法。这适用于存储所有问题共有的单独选项集。
CREATE TABLE choices (
choice_id integer primary key autoincrement,
choice string not null
);
CREATE TABLE questions (
ques_id integer primary key autoincrement,
ques string not null,
choice_id integer,
FOREIGN KEY(choice_id) REFERENCES choice(choice_id)
);
解释器会话示例:
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute("""CREATE TABLE choices (
... choice_id integer primary key autoincrement,
... choice string not null
... );""")
<sqlite3.Cursor object at 0x7f29f60b8ce8>
>>> c.execute("""CREATE TABLE questions (
... ques_id integer primary key autoincrement,
... ques string not null,
... choice_id integer,
... pub_date integer,
... FOREIGN KEY(choice_id) REFERENCES choice(choice_id)
... );""")
<sqlite3.Cursor object at 0x7f29f60b8ce8>
>>> c.execute("INSERT INTO choices (choice) VALUES ('yes')")
<sqlite3.Cursor object at 0x7f29f60b8ce8>
>>> c.execute("""INSERT INTO questions (ques,choice_id)
VALUES ('do you like sqlite?',1)""")
<sqlite3.Cursor object at 0x7f29f60b8ce8>
>>> c.execute("""SELECT ques, choice
FROM questions q
JOIN choices c ON c.choice_id = q.choice_id;""")
>>> c.fetchall()
[(u'do you like sqlite?', u'yes')]