简体   繁体   中英

Passing SQLite variables in Python

I am writing a app in python and utilzing sqlite. I have a list of strings which I would like to add too the database, where each element represents some data which coincides with the column it will be put.

currently I have something like this

cursor.execute("""insert into credit
                    values ('Citi','5567','visa',6000,9.99,'23',9000)""")

I can add strings easily but dont know how to add the variables of my list.

Use parameters to .execute() :

query = """
     INSERT INTO credit
         (bank, number, card, int1, value, type, int2)
     VALUES
          (?, ?, ?, ?, ?, ?, ?)
        """
data =  ['Citi', '5567', 'visa', 6000, 9.99, '23', 9000]

cursor.execute(query, data)

According to PEP249 :

.execute(operation[,parameters]) :

Prepare and execute a database operation (query or command). Parameters may be provided as sequence or mapping and will be bound to variables in the operation. Variables are specified in a database-specific notation (see the module's paramstyle attribute for details)

Checking paramstyle :

>>> import sqlite3
>>> print sqlite3.paramstyle
qmark

qmark means you use ? for parameters.

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