-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path02_crud_dbapi.py
More file actions
305 lines (242 loc) · 8.16 KB
/
Copy path02_crud_dbapi.py
File metadata and controls
305 lines (242 loc) · 8.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""02_crud_dbapi.py — CRUD with raw DB-API: Java JDBC → Python pycubrid.
Side-by-side migration from Java JDBC PreparedStatement to Python DB-API.
Each function shows the Java equivalent in its docstring.
Java JDBC pattern (what you're replacing):
──────────────────────────────────────────
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO cookbook_items (val, cnt) VALUES (?, ?)"
);
ps.setString(1, "widget");
ps.setInt(2, 10);
ps.executeUpdate();
conn.commit();
ps.close();
Python pycubrid (what you'll write):
─────────────────────────────────────
cursor.execute(
"INSERT INTO cookbook_items (val, cnt) VALUES (?, ?)",
("widget", 10),
)
conn.commit()
Same parameter marker (?), same SQL, 60% less boilerplate.
"""
from __future__ import annotations
import pycubrid
DB_CONFIG = {
"host": "localhost",
"port": 33000,
"database": "testdb",
"user": "dba",
"password": "",
}
def get_connection() -> pycubrid.Connection:
return pycubrid.connect(**DB_CONFIG)
def setup_table(conn: pycubrid.Connection) -> None:
"""CREATE TABLE — identical SQL in both languages.
Java:
stmt.executeUpdate("CREATE TABLE cookbook_items (...)");
conn.commit();
"""
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS cookbook_items")
cursor.execute("""
CREATE TABLE cookbook_items (
id INT AUTO_INCREMENT PRIMARY KEY,
val VARCHAR(200) NOT NULL,
cnt INT DEFAULT 0,
price DOUBLE DEFAULT 0.0
)
""")
conn.commit()
cursor.close()
print("Created table 'cookbook_items'")
def insert_single(conn: pycubrid.Connection) -> None:
"""INSERT one row with parameters.
Java (PreparedStatement):
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO cookbook_items (val, cnt, price) VALUES (?, ?, ?)"
);
ps.setString(1, "Widget A");
ps.setInt(2, 10);
ps.setDouble(3, 29.99);
ps.executeUpdate();
conn.commit();
ps.close();
Python — parameter tuple replaces setString/setInt/setDouble:
"""
cursor = conn.cursor()
cursor.execute(
"INSERT INTO cookbook_items (val, cnt, price) VALUES (?, ?, ?)",
("Widget A", 10, 29.99),
)
conn.commit()
cursor.close()
print("Inserted 1 row")
def insert_multiple(conn: pycubrid.Connection) -> None:
"""INSERT multiple rows.
Java:
for (Object[] row : data) {
ps.setString(1, (String) row[0]);
ps.setInt(2, (Integer) row[1]);
ps.setDouble(3, (Double) row[2]);
ps.executeUpdate();
}
conn.commit();
Python — executemany replaces the loop entirely:
"""
items = [
("Widget B", 5, 19.99),
("Gadget C", 20, 49.99),
("Part D", 100, 2.50),
("Tool E", 8, 34.99),
]
cursor = conn.cursor()
cursor.executemany(
"INSERT INTO cookbook_items (val, cnt, price) VALUES (?, ?, ?)",
items,
)
conn.commit()
cursor.close()
print(f"Inserted {len(items)} rows")
def select_all(conn: pycubrid.Connection) -> list[tuple]:
"""SELECT all rows.
Java (ResultSet iteration):
ResultSet rs = stmt.executeQuery("SELECT id, val, cnt, price FROM ...");
while (rs.next()) {
int id = rs.getInt("id");
String val = rs.getString("val");
int cnt = rs.getInt("cnt");
double price = rs.getDouble("price");
}
rs.close();
Python — fetchall() returns a list of tuples, no getInt/getString:
"""
cursor = conn.cursor()
cursor.execute("SELECT id, val, cnt, price FROM cookbook_items ORDER BY id")
rows = cursor.fetchall()
print(f"\nAll items ({len(rows)} rows):")
print(f" {'ID':>3s} {'Value':12s} {'Count':>5s} {'Price':>8s}")
for row in rows:
print(f" {row[0]:3d} {row[1]:12s} {row[2]:5d} ${row[3]:7.2f}")
cursor.close()
return rows
def select_filtered(conn: pycubrid.Connection) -> None:
"""SELECT with WHERE and parameters.
Java:
PreparedStatement ps = conn.prepareStatement(
"SELECT val, price FROM cookbook_items WHERE price > ? ORDER BY price DESC"
);
ps.setDouble(1, 20.0);
ResultSet rs = ps.executeQuery();
while (rs.next()) { ... }
Python — same ? marker, parameters as tuple:
"""
cursor = conn.cursor()
cursor.execute(
"SELECT val, price FROM cookbook_items WHERE price > ? ORDER BY price DESC",
(20.0,),
)
rows = cursor.fetchall()
print(f"\nItems over $20 ({len(rows)} rows):")
for row in rows:
print(f" {row[0]:12s} ${row[1]:.2f}")
cursor.close()
def select_fetchone(conn: pycubrid.Connection) -> None:
"""Fetch one row at a time (replaces rs.next() pattern).
Java:
rs.next(); // moves cursor forward, returns boolean
String val = rs.getString("val");
Python — fetchone() returns tuple or None:
"""
cursor = conn.cursor()
cursor.execute("SELECT val, cnt FROM cookbook_items ORDER BY id")
first = cursor.fetchone()
print(f"\nFirst item: {first[0]} (count={first[1]})")
second = cursor.fetchone()
print(f"Second item: {second[0]} (count={second[1]})")
cursor.close()
def update_rows(conn: pycubrid.Connection) -> None:
"""UPDATE rows.
Java:
PreparedStatement ps = conn.prepareStatement(
"UPDATE cookbook_items SET price = ? WHERE val = ?"
);
ps.setDouble(1, 24.99);
ps.setString(2, "Widget A");
int affected = ps.executeUpdate();
conn.commit();
Python — cursor.rowcount replaces executeUpdate return value:
"""
cursor = conn.cursor()
cursor.execute(
"UPDATE cookbook_items SET price = ? WHERE val = ?",
(24.99, "Widget A"),
)
print(f"\nUpdated Widget A price (rows affected: {cursor.rowcount})")
cursor.execute(
"UPDATE cookbook_items SET cnt = cnt + ? WHERE price < ?",
(10, 10.0),
)
print(f"Restocked cheap items (rows affected: {cursor.rowcount})")
conn.commit()
cursor.close()
def delete_rows(conn: pycubrid.Connection) -> None:
"""DELETE rows.
Java:
PreparedStatement ps = conn.prepareStatement(
"DELETE FROM cookbook_items WHERE val = ?"
);
ps.setString(1, "Tool E");
int affected = ps.executeUpdate();
conn.commit();
"""
cursor = conn.cursor()
cursor.execute("DELETE FROM cookbook_items WHERE val = ?", ("Tool E",))
print(f"\nDeleted Tool E (rows affected: {cursor.rowcount})")
conn.commit()
cursor.close()
def handle_nulls(conn: pycubrid.Connection) -> None:
"""NULL handling — much simpler in Python.
Java (the wasNull pattern):
int cnt = rs.getInt("cnt");
if (rs.wasNull()) {
// cnt is actually null, not 0
}
Python — NULL becomes None, no wasNull() needed:
"""
cursor = conn.cursor()
cursor.execute(
"INSERT INTO cookbook_items (val, cnt, price) VALUES (?, NULL, NULL)",
("NullTest",),
)
conn.commit()
cursor.execute(
"SELECT val, cnt, price FROM cookbook_items WHERE val = ?",
("NullTest",),
)
row = cursor.fetchone()
print(f"\nNull handling: val={row[0]!r}, cnt={row[1]!r}, price={row[2]!r}")
cursor.close()
def cleanup(conn: pycubrid.Connection) -> None:
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS cookbook_items")
conn.commit()
cursor.close()
print("\nCleaned up table 'cookbook_items'")
if __name__ == "__main__":
conn = get_connection()
try:
setup_table(conn)
insert_single(conn)
insert_multiple(conn)
select_all(conn)
select_filtered(conn)
select_fetchone(conn)
update_rows(conn)
select_all(conn)
delete_rows(conn)
select_all(conn)
handle_nulls(conn)
finally:
cleanup(conn)
conn.close()