简体   繁体   English

如何获取输入变量以存储在sqlite3表中?

[英]How can I get input variables to be stored in a sqlite3 table?

I am trying to get the user input the information so it can be stored in a database using SQLite3 but the error: " sqlite3.OperationalError: no such column: first_name " keeps popping up and I don't know why. 我试图让用户输入信息,以便可以使用SQLite3将其存储在数据库中,但是错误:“ sqlite3.OperationalError:没有这样的列:first_name ”不断弹出,我不知道为什么。 Any suggestions? 有什么建议么?

    import sqlite3

    connection = sqlite3.connect('database.db')
    cursor = connection.cursor()
    create_table = '''
    CREATE TABLE example (
    fname VARCHAR(20),
    lname VARCHAR(30),
    gender CHAR(1));'''
    cursor.execute(create_table)

    first_name = input('First name : ')
    surname = input('surname: ')
    gend = input('Gender: ')

    add_staff = '''INSERT INTO example (fname, lname, gender)
        VALUES (first_name, surname, gend);'''
    cursor.execute(add_staff)

    cursor.execute('SELECT * FROM example')
    result = cursor.fetchall()
    for r in result:
        print(r)
    cursor.execute('SELECT * FROM example')

I would like to stick to sqlite3 rather than using another database library within python. 我想坚持使用sqlite3,而不是在python中使用另一个数据库库。 Thanks. 谢谢。

You need to pass the values of your variables to your SQL command, using placeholders. 您需要使用占位符将变量的值传递给SQL命令。

add_staff = '''INSERT INTO example (fname, lname, gender)
    VALUES (?, ?, ?);'''
cursor.execute(add_staff, (first_name, surname, gend))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM