Skip to content

Commit fe89081

Browse files
Merge pull request #169 from codewizardshq/add-executescript-docs
Add `cursor.executescript()` docs to Python-SQL docs.
2 parents 70edb18 + cb4f0a9 commit fe89081

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

docs/python/python-language.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2164,6 +2164,61 @@ query = """
21642164
cursor.execute(query)
21652165
```
21662166

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+
CREATE TABLE IF NOT EXISTS users (
2195+
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
2196+
username TEXT UNIQUE NOT NULL,
2197+
password TEXT NOT 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+
21672222
##### `Modifying SQL DBs from Python`
21682223

21692224
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

Comments
 (0)