如何在SQLITE3语句中表达python变量

时间:2018-04-20 17:55:45

标签: python sqlite

我创建了以下函数来创建表调用user

import sqlite3
from datetime import datetime


def create_connection(db_file):
    try:
        connection = sqlite3.connect(db_file)
        return connection
    except sqlite3.Error as e:
        print(e)
    return None


def create_table(connection, sql_table):
    cursor = connection.cursor() 
    with connection:
        try:
            cursor.execute(sql_table) 
        except sqlite3.Error as e:
            print(e)


def insert_user(connection, date, username):
    cursor = connection.cursor() 
    with connection:
        cursor.execute("INSERT INTO user VALUES(?,?)",(date, username))


database = "test.db"

user_table = """ CREATE TABLE IF NOT EXISTS user (
                    date      TEXT    NOT NULL,
                    username  TEXT    NOT NULL
             ); """

conn = create_connection(database)
create_table(conn, user_table)
date = datetime.now().strftime('%Y-%m-%d')
username = 'user1'
insert_user(conn, date, username)

我想使函数insert_user更通用。我希望能够将user传递给此函数,而不必在

中明确写入user
cursor.execute("INSERT INTO user VALUES(?,?)",(date, username))

同样,我想避免在

中明确地写user
user_table = """ CREATE TABLE IF NOT EXISTS user (

相反,我希望变量具有值user并将该变量传递给此语句。

我应该如何修改我的代码?感谢。

0 个答案:

没有答案