You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/python/python-language.md
+55Lines changed: 55 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2164,6 +2164,61 @@ query = """
2164
2164
cursor.execute(query)
2165
2165
```
2166
2166
2167
+
If you need to run multiple statements, you can use the `cursor.executescript()` method. It takes a `str` of the different SQL statements as an argument. Note that each statement must end with a semicolon when using `cursor.executescript()`:
2168
+
2169
+
```python
2170
+
import sqlite3
2171
+
2172
+
connection = sqlite3.connect("user-info.db")
2173
+
cursor = connection.cursor()
2174
+
2175
+
script ="""
2176
+
CREATE TABLE IF NOT EXISTS users (
2177
+
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
2178
+
username TEXT UNIQUE NOT NULL,
2179
+
password TEXT NOT NULL
2180
+
);
2181
+
2182
+
INSERT INTO users (username, password) VALUES ('steve', 'm!necr@ft');
2183
+
INSERT INTO users (username, password) VALUES ('mario', 'mu$hr00m@n');
2184
+
"""
2185
+
2186
+
cursor.executescript(script)
2187
+
```
2188
+
2189
+
When using `cursor.executescript()`, you can pull the `script` from a file as well:
2190
+
2191
+
*script.sql*
2192
+
2193
+
```sql
2194
+
CREATETABLEIF NOT EXISTS users (
2195
+
user_id INTEGERPRIMARY KEY AUTOINCREMENT,
2196
+
username TEXT UNIQUE NOT NULL,
2197
+
password TEXTNOT NULL
2198
+
);
2199
+
2200
+
INSERT INTO users (username, password) VALUES ('steve', 'm!necr@ft');
2201
+
INSERT INTO users (username, password) VALUES ('mario', 'mu$hr00m@n');
2202
+
```
2203
+
2204
+
*main.py*
2205
+
2206
+
```python
2207
+
import sqlite3
2208
+
2209
+
connection = sqlite3.connect("user-info.db")
2210
+
cursor = connection.cursor()
2211
+
2212
+
file=open("script.sql", "r")
2213
+
script =file.read()
2214
+
2215
+
cursor.executescript(script)
2216
+
```
2217
+
2218
+
!!! note
2219
+
2220
+
The `cursor.executescript()` method should only be used to do things like create tables, insert values, etc. You can't use it with `SELECT` statements.
2221
+
2167
2222
##### `Modifying SQL DBs from Python`
2168
2223
2169
2224
If your query modifies the database (as `INSERT`, `UPDATE`, and `DELETE` queries do) you'll need to use the `connection.commit()` method to ensure the changes are stored in the DB:
0 commit comments