python list to sqlite3
时间: 2023-10-16 21:10:08 浏览: 88
python 用sqlite3
3星 · 编辑精心推荐
To insert a Python list into an SQLite3 database, you can use the `executemany()` method of the SQLite3 cursor object. Here is an example code snippet:
```
import sqlite3
# create a connection to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# create a table to store the list elements
cursor.execute('''CREATE TABLE list_elements (value TEXT)''')
# example list
my_list = ['apple', 'banana', 'orange']
# insert the list elements into the database
values = [(elem,) for elem in my_list]
cursor.executemany('INSERT INTO list_elements VALUES (?)', values)
# commit the changes and close the connection
conn.commit()
conn.close()
```
In this code, we first create a connection to the SQLite3 database and create a cursor object. Then, we create a table called `list_elements` with a single column `value` of type `TEXT`.
Next, we define an example Python list called `my_list` and create a list of tuples containing the list elements. The tuples are necessary because the `executemany()` method expects a list of tuples as input.
Finally, we use the `executemany()` method to insert the list elements into the `list_elements` table. The `?` character is a placeholder for the value that will be inserted, and the `values` variable contains a list of tuples that will be used to fill in the placeholders.
After committing the changes to the database, we close the connection.
阅读全文