将行插入 SQLite table
Inserting row into SQLite table
我正在尝试将一行(post 由用户提交)添加到 SQLite table (posts) 中。
我需要添加新的 post,时间戳是当前时间和日期,然后我需要 return 这个新的 post.
的 ID
到目前为止我的代码(不完整,因为我不确定如何 return id 以及我是否插入正确的信息):
def post_add(conn, username, message):
cursor = conn.cursor()
cursor.execute("INSERT INTO posts (timestamp, username, message) VALUES (CURRENT_TIMESTAMP,?,?)"
, (username, message))
db.commit()
table:
CREATE TABLE posts (
id integer unique primary key autoincrement,
timestamp text default CURRENT_TIMESTAMP,
username text,
message text,
FOREIGN KEY(username) REFERENCES users(name)
);
游标对象在其 lastrowid
属性中有最后一个插入 ID。
cursor.execute('INSERT ...')
new_id = cursor.lastrowid
db.commit()
return new_id
您可以使用类似的东西:
def post_add(db, usernick, message):
cursor = db.cursor()
cursor.execute("INSERT INTO posts (usernick, content) VALUES (?,?)"
,(usernick, message))
inserted_id = cursor.lastrowid
db.commit()
return inserted_id
至于文本大小限制,我不知道在 sqlite 中有什么方法可以做到这一点,但是您可以在 python 中检查它,例如在函数的开头添加这两行:
if len(message) > MAX_ALLOWED_LENGTH:
return None
我正在尝试将一行(post 由用户提交)添加到 SQLite table (posts) 中。 我需要添加新的 post,时间戳是当前时间和日期,然后我需要 return 这个新的 post.
的 ID到目前为止我的代码(不完整,因为我不确定如何 return id 以及我是否插入正确的信息):
def post_add(conn, username, message):
cursor = conn.cursor()
cursor.execute("INSERT INTO posts (timestamp, username, message) VALUES (CURRENT_TIMESTAMP,?,?)"
, (username, message))
db.commit()
table:
CREATE TABLE posts (
id integer unique primary key autoincrement,
timestamp text default CURRENT_TIMESTAMP,
username text,
message text,
FOREIGN KEY(username) REFERENCES users(name)
);
游标对象在其 lastrowid
属性中有最后一个插入 ID。
cursor.execute('INSERT ...')
new_id = cursor.lastrowid
db.commit()
return new_id
您可以使用类似的东西:
def post_add(db, usernick, message):
cursor = db.cursor()
cursor.execute("INSERT INTO posts (usernick, content) VALUES (?,?)"
,(usernick, message))
inserted_id = cursor.lastrowid
db.commit()
return inserted_id
至于文本大小限制,我不知道在 sqlite 中有什么方法可以做到这一点,但是您可以在 python 中检查它,例如在函数的开头添加这两行:
if len(message) > MAX_ALLOWED_LENGTH:
return None