简体   繁体   中英

Python and SQLite storing variables

If I the following code, how do I insert my string 'test' into the database

connection = connect(database = 'orders.db')
orders_db = connection.cursor()

test = 'Product 1'

sql = """INSERT INTO `CustomerOrders`(Product) VALUES(?)"""
orders_db.execute(sql)

connection.commit()

orders_db.close()
connection.close()

This should do it !

(test,) here the comma is required,without it the intrepreter will throw an error since it takes each characters as an argument!

import sqlite3
connection = sqlite3.connect(database = 'orders.db')
connection.execute('''Create table if not exists CustomerOrders(Product Varchar(100))''')
orders_db = connection.cursor()

test = 'Product 1'

sql = """INSERT INTO CustomerOrders(Product) VALUES(?)"""
orders_db.execute(sql,(test,))

connection.commit()

orders_db.close()
connection.close()

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