I have a list of tuples:
list_ = [(1,7,3000),(1,8,3500), (1,9,3900)]
I want to update a table with multiple rows/values for a given ID (in this case ID = 1)
So:
INSERT INTO table (ID, Speed, Power) VALUES (1,7,3000),(1,8,3500),(1,9,3900)
I'm having trouble with the format - I've gotten the string down to something like this:
INSERT INTO ... VALUES ((1,7,3000),(1,8,3500),(1,9,3900))
But of course this doesn't work due to the extra parenthesis wrapped around the tuples. Any ideas for constructing a way to do this "pythonically?
To insert multiple rows into a table, use the executemany() method.
INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.
Create a connection object using the mysql. connector. connect() method, by passing the user name, password, host (optional default: localhost) and, database (optional) as parameters to it. Then, execute the INSERT statement by passing it as a parameter to the execute() method.
The number of rows that you can insert at a time is 1,000 rows using this form of the INSERT statement. If you want to insert more rows than that, you should consider using multiple INSERT statements, BULK INSERT or a derived table.
The idiomatic way to handle this in Python is to use the executemany method of the cursor provided by the database driver that is being used.
For example, for sqlite using the sqlite3 module in the standard library
conn = sqlite3.connect('/path/to/file.db')
cursor = conn.cursor()
sql = """INSERT INTO mytable (ID, Speed, Power) VALUES (?, ?, ?)"""
values = [(1,7,3000),(1,8,3500),(1,9,3900)]
cursor.executemany(stmt, values)
The placeholder used in the VALUES
clause varies by the specific driver. The correct value can be found in the driver's documentation or by looking up the driver module's paramstyle attribute.
Using this approach instead of string interpolation / formatting or f-strings ensures that values are correctly quoted, which guards against SQL injection and other errors:
>>> conn = sqlite3.connect(':memory:')
>>> cur = conn.cursor()
>>> date = '2020-11-23'
>>> # Correctly quoted input is returned as the selected value
>>> cur.execute("""SELECT ? AS today""", (date,)) # <- execute requires a tuple as values
<sqlite3.Cursor object at 0x7f1fa205e1f0>
>>> cur.fetchone()
('2020-11-23',)
>>> # Unquoted input is evaluated as an expression!
>>> cur.execute(f"""SELECT {date} AS today""")
<sqlite3.Cursor object at 0x7f1fa205e1f0>
>>> cur.fetchone()
(1986,)
Here's an example of an SQL injection using string formatting. Because the value "name" is not escaped, the query returns all the usernames and passwords in the table when the programmer's intention was only to return one.
NAMES = [('Alice', 'apple'), ('Bob', 'banana'), ('Carol', 'cherry')]
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute("""CREATE TABLE users (name text, password text)""")
cur.executemany("""INSERT INTO users (name, password) VALUES (?, ?)""", NAMES)
conn.commit()
cur.execute("""SELECT name, password FROM users WHERE name = {}""".format('name'))
for row in cur.fetchall():
print(row)
If the value were escaped correctly:
cur.execute("""SELECT name, password FROM users WHERE name = ?""", ('name',))
no rows would be returned, defeating the attack.
Well, you need to construct the line:
INSERT INTO ... VALUES (1,7,3000), (1,8,3500), (1,9,3900)
Try that one:
rows = [(1,7,3000), (1,8,3500), (1,9,3900)]
values = ', '.join(map(str, rows))
sql = "INSERT INTO ... VALUES {}".format(values)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With