简体   繁体   中英

How can I use column names to specify what to write to using sqlite3?

For example, I want to create a function where I add a user to my 'users' table:

def add_user(name, id):
    cursor.execute("INSERT INTO users VALUES (?, ?, ?)", (name, id))
    conn.commit()

(It should be noted that the 'name' column (not the variable) is the first column, and the 'id' column is the third column)

This code writes the 'name' variable to the first column, which is the name column, and writes the 'id' variable to the second column (which is not the id column).

Is there a way I can use the names of the columns to specify what to write to? I want to avoid using solutions like writing the current value of the second column to itself, or adding 0 to it, or something like that.

First, you are using 3 ? placeholders and pass only 2 values: name and id , so your code would not even run.

In the INSERT statement, you can specify the columns that will receive the values that you supply as a tuple:

cursor.execute("INSERT INTO users(name, id) VALUES (?, ?)", (name, id))

or:

cursor.execute("INSERT INTO users(id, name) VALUES (?, ?)", (id, name))

In both cases the result is the same.

With INSERT INTO users(id, name)... the 1st ? corresponds to the value of the column id and the 2nd ? corresponds to the value of the column name , so you must pass their values inside the tuple in the same order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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