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
The pandas `DataFrame.to_sql` function documentation in the above code block can be found here: [pandas.DataFrame.to_sql](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html)
75
71
76
72
```python
77
73
# Read data from newly created table, passing in existing movies_db connection as parameter
78
-
new_movies_df = pd.read_sql_query('Select * from new_movie_table;', movies_db)
74
+
new_movies_df = pd.read_sql_query('SELECT * FROM updated_movies;', movies_db)
Copy file name to clipboardExpand all lines: content/python-pandas-databases/reading/python-databases/_index.md
+81-2Lines changed: 81 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -12,6 +12,26 @@ Working within a database command line interface can oftentimes make it cumberso
12
12
13
13
While you can accomplish more than just the above using python and pandas, like performing joins, it is not always best practice. As it relates to joins, database engines are built and optimized to perform joins extremely well. It is always important to know what you will be doing with your data before acting.
14
14
15
+
## When to Use sqlite3 vs pandas
16
+
17
+
Understanding when to use each tool will help you write more efficient code:
- Working with large datasets that don't fit in memory
22
+
- You need precise control over transactions and commits
23
+
- Creating or modifying database schema (tables, indexes, constraints)
24
+
- The data will remain in the database without further analysis
25
+
26
+
**Use pandas when:**
27
+
- You need to perform complex data analysis or visualization
28
+
- Applying statistical operations or transformations
29
+
- Cleaning and reshaping data
30
+
- Integrating database data with other data sources
31
+
- The dataset is small to medium-sized and fits in memory
32
+
33
+
**Best Practice:** Use sqlite3 to filter and join data in the database, then load the results into pandas for analysis. This leverages the strengths of both tools!
34
+
15
35
{{% notice red Warning "rocket" %}}
16
36
We have created a new repo for Class 19 and 20 exercises and studios.
17
37
Please fork this repo to your Github account, and then clone it to your local device
@@ -63,6 +83,26 @@ The basic syntax for executing a command with the cursor object is as follows:
63
83
cur.execute("SQL statement")
64
84
```
65
85
86
+
## Using Context Managers
87
+
88
+
A better practice for managing database connections is to use Python's context manager pattern with the `with` statement. This ensures that connections are properly closed even if an error occurs:
89
+
90
+
{{% notice blue Example "rocket" %}}
91
+
```python
92
+
import sqlite3
93
+
94
+
# Using a context manager - connection closes automatically
95
+
with sqlite3.connect('Movies.db') as movies_db:
96
+
cur = movies_db.cursor()
97
+
cur.execute("SELECT * FROM movies")
98
+
results = cur.fetchall()
99
+
print(results)
100
+
# Connection is automatically closed here
101
+
```
102
+
103
+
This pattern is especially useful when performing multiple operations, as it guarantees proper cleanup.
104
+
{{% /notice %}}
105
+
66
106
## Creating a table
67
107
68
108
```python
@@ -76,7 +116,9 @@ You can find a list of SQLite data types here: [Data Types in SQLite](https://sq
76
116
### Insert Table Values
77
117
78
118
```python
79
-
cur.execute("INSERT INTO table_name ('value-one', 'value-two', etc..)")
119
+
cur.execute("INSERT INTO table_name (column1, column2) VALUES ('value-one', 'value-two')")
120
+
# Commit the changes to save them to the database
121
+
movies_db.commit()
80
122
```
81
123
82
124
### Reading Data
@@ -87,7 +129,7 @@ There are a couple strategies that you can use to read data from your database.
87
129
88
130
```python
89
131
# For loop to iterate over cursor object
90
-
for row in cur.execute("SELECT column FROM table_name")
132
+
for row in cur.execute("SELECT column FROM table_name"):
91
133
print(row)
92
134
```
93
135
@@ -113,6 +155,8 @@ update_release_year = 1997 # Value that needs to be updated
113
155
movie_to_update ='Good Will Hunting'
114
156
# Execute an UPDATE statement using the ? placeholder, passing in the update variables as a list literal
115
157
cur.execute("UPDATE movies SET release = ? WHERE title = ?", [update_release_year, movie_to_update])
158
+
# Commit the changes to save them to the database
159
+
movies_db.commit()
116
160
```
117
161
{{% /notice %}}
118
162
@@ -126,9 +170,44 @@ Using parameterized queries to update and delete data is a best practice!
126
170
movie_to_delete ='Inception'# Too many sci fi movies!
127
171
# Execute a DELETE statement using the ? placeholder, passing in the variable as a list literal
128
172
cur.execute("DELETE FROM movies WHERE title = ?", [movie_to_delete])
173
+
# Commit the changes to save them to the database
174
+
movies_db.commit()
129
175
```
130
176
{{% /notice %}}
131
177
178
+
## Error Handling
179
+
180
+
When working with databases, it's important to handle potential errors gracefully. Common errors include trying to access tables that don't exist, constraint violations, or connection issues.
181
+
182
+
{{% notice blue Example "rocket" %}}
183
+
```python
184
+
import sqlite3
185
+
186
+
try:
187
+
with sqlite3.connect('Movies.db') as movies_db:
188
+
cur = movies_db.cursor()
189
+
190
+
# Attempt to insert a duplicate record or violate a constraint
191
+
cur.execute("INSERT INTO movies (title, genre, release) VALUES (?, ?, ?)",
192
+
['Inception', 'Sci-Fi', 2010])
193
+
movies_db.commit()
194
+
195
+
except sqlite3.IntegrityError as e:
196
+
print(f"Database integrity error: {e}")
197
+
198
+
except sqlite3.OperationalError as e:
199
+
print(f"Database operational error (table may not exist): {e}")
200
+
201
+
except sqlite3.Error as e:
202
+
print(f"Database error: {e}")
203
+
204
+
exceptExceptionas e:
205
+
print(f"Unexpected error: {e}")
206
+
```
207
+
208
+
Using try-except blocks helps your program handle errors without crashing and provides useful feedback.
0 commit comments