dc-cmnutils 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,283 @@
1
+ from typing import Any, List, Dict, Optional, Tuple, Union
2
+ import traceback
3
+
4
+
5
+ class DbOperator:
6
+ """
7
+ 通用数据库操作封装类
8
+ 适配所有遵循 Python DB-API 2.0 规范的数据库连接对象
9
+ 使用方式:外部创建数据库 connection,传入本类构造函数
10
+ 支持: 单条查询、多条查询、分页查询、插入、批量插入、更新、删除基础CRUD
11
+ 特性:参数化防SQL注入、事务自动提交/回滚、游标自动关闭、异常堆栈打印
12
+ """
13
+
14
+ def __init__(self, db_conn: Any):
15
+ """
16
+ 初始化数据库操作对象
17
+ :param db_conn: 数据库连接对象(必须遵循 DB-API2 规范)
18
+ sqlite3.Connection / pymysql.connections.Connection / psycopg2.extensions.connection 等
19
+ """
20
+ self._conn = db_conn
21
+ # 校验连接对象合法性
22
+ if not hasattr(self._conn, "cursor") or not hasattr(self._conn, "commit"):
23
+ raise TypeError("传入对象不是合法的 DB-API2 数据库连接对象")
24
+
25
+ def query_one(self, sql: str, params: Union[Tuple, List, Dict] = ()) -> Optional[Dict[str, Any]]:
26
+ """
27
+ 查询单条数据,返回字典格式 {字段名: 值}
28
+ :param sql: 查询SQL语句,占位符遵循对应数据库驱动规则 (%s / ? / :name)
29
+ :param params: SQL参数,元组/列表/字典,用于参数化防注入
30
+ :return: 单行字典,无数据返回 None
31
+ """
32
+ cursor = None
33
+ try:
34
+ cursor = self._conn.cursor()
35
+ cursor.execute(sql, params)
36
+ row = cursor.fetchone()
37
+ if row is None:
38
+ return None
39
+ # 列名与值映射为字典
40
+ col_names = [desc[0] for desc in cursor.description]
41
+ return dict(zip(col_names, row))
42
+ except Exception as e:
43
+ self._conn.rollback()
44
+ raise RuntimeError(f"query_one 执行异常: {str(e)}\n{traceback.format_exc()}") from e
45
+ finally:
46
+ if cursor:
47
+ cursor.close()
48
+
49
+ def query_many(self, sql: str, params: Union[Tuple, List, Dict] = ()) -> List[Dict[str, Any]]:
50
+ """
51
+ 查询多条数据,返回列表嵌套字典
52
+ :param sql: 查询SQL语句
53
+ :param params: SQL参数
54
+ :return: 列表,元素为单行字典,无数据返回空列表
55
+ """
56
+ cursor = None
57
+ try:
58
+ cursor = self._conn.cursor()
59
+ cursor.execute(sql, params)
60
+ rows = cursor.fetchall()
61
+ if not rows:
62
+ return []
63
+ col_names = [desc[0] for desc in cursor.description]
64
+ return [dict(zip(col_names, row)) for row in rows]
65
+ except Exception as e:
66
+ self._conn.rollback()
67
+ raise RuntimeError(f"query_many 执行异常: {str(e)}\n{traceback.format_exc()}") from e
68
+ finally:
69
+ if cursor:
70
+ cursor.close()
71
+
72
+ def query_page(self, sql: str, page_num: int, page_size: int, params: Union[Tuple, List, Dict] = ()) -> Dict[str, Any]:
73
+ """
74
+ 通用分页查询
75
+ :param sql: 基础查询SQL(不要加limit偏移)
76
+ :param page_num: 页码,从1开始
77
+ :param page_size: 每页条数
78
+ :param params: SQL查询参数
79
+ :return: 字典 {total:总条数, page_num:当前页, page_size:页大小, data:当前页数据列表}
80
+ """
81
+ if page_num < 1 or page_size < 1:
82
+ raise ValueError("页码与每页条数必须大于0")
83
+
84
+ cursor = None
85
+ try:
86
+ cursor = self._conn.cursor()
87
+ # 1. 查询总条数
88
+ count_sql = f"SELECT COUNT(*) FROM ({sql}) AS _temp_count"
89
+ cursor.execute(count_sql, params)
90
+ total = cursor.fetchone()[0]
91
+
92
+ # 2. 分页拼接 LIMIT 偏移(兼容SQLite/MySQL通用写法)
93
+ offset = (page_num - 1) * page_size
94
+ page_sql = f"{sql} LIMIT ? OFFSET ?"
95
+ page_params = list(params) + [page_size, offset]
96
+ cursor.execute(page_sql, page_params)
97
+ rows = cursor.fetchall()
98
+
99
+ if not rows:
100
+ data_list = []
101
+ else:
102
+ col_names = [desc[0] for desc in cursor.description]
103
+ data_list = [dict(zip(col_names, row)) for row in rows]
104
+
105
+ return {
106
+ "total": total,
107
+ "page_num": page_num,
108
+ "page_size": page_size,
109
+ "data": data_list
110
+ }
111
+ except Exception as e:
112
+ self._conn.rollback()
113
+ raise RuntimeError(f"query_page 分页查询异常: {str(e)}\n{traceback.format_exc()}") from e
114
+ finally:
115
+ if cursor:
116
+ cursor.close()
117
+
118
+ def insert(self, sql: str, params: Union[Tuple, List, Dict] = ()) -> int:
119
+ """
120
+ 执行单条插入语句,返回受影响行数
121
+ :param sql: INSERT SQL语句
122
+ :param params: SQL参数
123
+ :return: 插入影响行数
124
+ """
125
+ cursor = None
126
+ try:
127
+ cursor = self._conn.cursor()
128
+ cursor.execute(sql, params)
129
+ self._conn.commit()
130
+ return cursor.rowcount
131
+ except Exception as e:
132
+ self._conn.rollback()
133
+ raise RuntimeError(f"insert 执行异常: {str(e)}\n{traceback.format_exc()}") from e
134
+ finally:
135
+ if cursor:
136
+ cursor.close()
137
+
138
+ def batch_insert(self, sql: str, params_list: List[Union[Tuple, List, Dict]]) -> int:
139
+ """
140
+ 批量插入数据(executemany 高性能批量写入)
141
+ :param sql: INSERT 模板SQL
142
+ :param params_list: 多行参数组成的列表,每个元素为单行参数
143
+ :return: 总共插入影响行数
144
+ """
145
+ if not isinstance(params_list, list) or len(params_list) == 0:
146
+ return 0
147
+
148
+ cursor = None
149
+ try:
150
+ cursor = self._conn.cursor()
151
+ cursor.executemany(sql, params_list)
152
+ self._conn.commit()
153
+ return cursor.rowcount
154
+ except Exception as e:
155
+ self._conn.rollback()
156
+ raise RuntimeError(f"batch_insert 批量插入异常: {str(e)}\n{traceback.format_exc()}") from e
157
+ finally:
158
+ if cursor:
159
+ cursor.close()
160
+
161
+ def update(self, sql: str, params: Union[Tuple, List, Dict] = ()) -> int:
162
+ """
163
+ 执行更新语句,返回受影响行数
164
+ :param sql: UPDATE SQL语句
165
+ :param params: SQL参数
166
+ :return: 更新影响行数
167
+ """
168
+ cursor = None
169
+ try:
170
+ cursor = self._conn.cursor()
171
+ cursor.execute(sql, params)
172
+ self._conn.commit()
173
+ return cursor.rowcount
174
+ except Exception as e:
175
+ self._conn.rollback()
176
+ raise RuntimeError(f"update 执行异常: {str(e)}\n{traceback.format_exc()}") from e
177
+ finally:
178
+ if cursor:
179
+ cursor.close()
180
+
181
+ def delete(self, sql: str, params: Union[Tuple, List, Dict] = ()) -> int:
182
+ """
183
+ 执行删除语句,返回受影响行数
184
+ :param sql: DELETE SQL语句
185
+ :param params: SQL参数
186
+ :return: 删除影响行数
187
+ """
188
+ cursor = None
189
+ try:
190
+ cursor = self._conn.cursor()
191
+ cursor.execute(sql, params)
192
+ self._conn.commit()
193
+ return cursor.rowcount
194
+ except Exception as e:
195
+ self._conn.rollback()
196
+ raise RuntimeError(f"delete 执行异常: {str(e)}\n{traceback.format_exc()}") from e
197
+ finally:
198
+ if cursor:
199
+ cursor.close()
200
+
201
+ def close(self) -> None:
202
+ """关闭数据库连接"""
203
+ if self._conn:
204
+ self._conn.close()
205
+
206
+ @property
207
+ def connection(self):
208
+ """对外暴露原始连接对象,用于复杂自定义操作、自定义事务逻辑"""
209
+ return self._conn
210
+
211
+
212
+
213
+ import sqlite3
214
+ # from dc.cmnutils.database.db_operater import DbOperator
215
+
216
+
217
+ def main():
218
+ # 1. 创建原生数据库连接(sqlite3 标准库内置,无需安装第三方包)
219
+ # 你可替换为 pymysql / psycopg2 / pyodbc 等任意数据库连接
220
+ conn = sqlite3.connect("test_db.db")
221
+
222
+ # 2. 实例化通用数据库操作类,传入原生连接对象
223
+ db = DbOperator(conn)
224
+
225
+ try:
226
+ # ==================== 1. 建表 ====================
227
+ create_table_sql = """
228
+ CREATE TABLE IF NOT EXISTS user_info (
229
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
230
+ username TEXT NOT NULL,
231
+ age INTEGER,
232
+ email TEXT
233
+ )
234
+ """
235
+ cur = conn.cursor()
236
+ cur.execute(create_table_sql)
237
+ conn.commit()
238
+ cur.close()
239
+ print("表初始化完成\n")
240
+
241
+ # ==================== 2. 插入数据 insert ====================
242
+ insert_sql = "INSERT INTO user_info (username, age, email) VALUES (?, ?, ?)"
243
+ row_effect = db.insert(insert_sql, ("zhangsan", 22, "zhangsan@example.com"))
244
+ print(f"插入成功,影响行数: {row_effect}\n")
245
+
246
+ # 批量插入演示(多次调用insert,也可自行封装executemany)
247
+ db.insert(insert_sql, ("lisi", 25, "lisi@example.com"))
248
+
249
+ # ==================== 3. 查询单条 query_one ====================
250
+ one_row = db.query_one("SELECT * FROM user_info WHERE username = ?", ("zhangsan",))
251
+ print("查询单条结果:")
252
+ print(one_row)
253
+ print()
254
+
255
+ # ==================== 4. 查询多条 query_many ====================
256
+ all_rows = db.query_many("SELECT * FROM user_info")
257
+ print("查询全部数据:")
258
+ for item in all_rows:
259
+ print(item)
260
+ print()
261
+
262
+ # ==================== 5. 更新数据 update ====================
263
+ update_sql = "UPDATE user_info SET age = ? WHERE username = ?"
264
+ update_cnt = db.update(update_sql, (26, "lisi"))
265
+ print(f"更新行数: {update_cnt}")
266
+ print("更新后数据:", db.query_one("SELECT * FROM user_info WHERE username = ?", ("lisi",)))
267
+ print()
268
+
269
+ # ==================== 6. 删除数据 delete ====================
270
+ delete_sql = "DELETE FROM user_info WHERE username = ?"
271
+ del_cnt = db.delete(delete_sql, ("zhangsan",))
272
+ print(f"删除行数: {del_cnt}")
273
+ print("删除后全部数据:", db.query_many("SELECT * FROM user_info"))
274
+
275
+ except Exception as e:
276
+ print(f"程序运行异常: {e}")
277
+ finally:
278
+ # 关闭连接
279
+ db.close()
280
+
281
+
282
+ if __name__ == "__main__":
283
+ main()
@@ -0,0 +1,389 @@
1
+ # import logging
2
+ # from typing import List, Optional, Tuple, Dict, Union
3
+ # # import pandas as pd
4
+ # from enum import Enum
5
+ #
6
+ # # 根据安装的驱动选择导入
7
+ # try:
8
+ # import pyodbc
9
+ # except ImportError:
10
+ # pyodbc = None
11
+ #
12
+ # try:
13
+ # import pymysql
14
+ # except ImportError:
15
+ # pymysql = None
16
+ #
17
+ # try:
18
+ # import cx_Oracle
19
+ # except ImportError:
20
+ # cx_Oracle = None
21
+ #
22
+ # try:
23
+ # import sqlite3
24
+ # except ImportError:
25
+ # sqlite3 = None
26
+ #
27
+ #
28
+ # class DatabaseType(Enum):
29
+ # """数据库类型枚举"""
30
+ # SQLSERVER = "sqlserver"
31
+ # MYSQL = "mysql"
32
+ # ORACLE = "oracle"
33
+ # SQLITE = "sqlite"
34
+ #
35
+ #
36
+ # class DbUtil:
37
+ # """数据库操作工具类,支持多种数据库"""
38
+ #
39
+ # def __init__(self, db_type: Union[DatabaseType, str], **kwargs):
40
+ # """
41
+ # 初始化数据库连接
42
+ #
43
+ # Args:
44
+ # db_type: 数据库类型,可以是DatabaseType枚举或字符串
45
+ # **kwargs: 数据库连接参数,根据数据库类型不同而不同
46
+ #
47
+ # For SQL Server:
48
+ # - server: 服务器地址
49
+ # - database: 数据库名
50
+ # - username: 用户名
51
+ # - password: 密码
52
+ # - driver: ODBC驱动(可选)
53
+ #
54
+ # For MySQL:
55
+ # - host: 主机地址
56
+ # - database: 数据库名
57
+ # - user: 用户名
58
+ # - password: 密码
59
+ # - port: 端口(可选,默认3306)
60
+ #
61
+ # For Oracle:
62
+ # - dsn: 数据源名称
63
+ # - user: 用户名
64
+ # - password: 密码
65
+ #
66
+ # For SQLite:
67
+ # - database: 数据库文件路径
68
+ # """
69
+ # # 设置日志
70
+ # self.logger = logging.getLogger(__name__)
71
+ #
72
+ # # 确定数据库类型
73
+ # if isinstance(db_type, str):
74
+ # try:
75
+ # self.db_type = DatabaseType(db_type.lower())
76
+ # except ValueError:
77
+ # raise ValueError(f"不支持的数据库类型: {db_type}")
78
+ # else:
79
+ # self.db_type = db_type
80
+ #
81
+ # self.connection = None
82
+ # self.connect(**kwargs)
83
+ #
84
+ # def connect(self, **kwargs) -> None:
85
+ # """建立数据库连接"""
86
+ # try:
87
+ # if self.db_type == DatabaseType.SQLSERVER:
88
+ # if pyodbc is None:
89
+ # raise ImportError("请安装pyodbc库: pip install pyodbc")
90
+ #
91
+ # server = kwargs.get('server', 'localhost')
92
+ # database = kwargs.get('database', 'master')
93
+ # username = kwargs.get('username', 'sa')
94
+ # password = kwargs.get('password', '')
95
+ # driver = kwargs.get('driver', '{ODBC Driver 17 for SQL Server}')
96
+ #
97
+ # conn_str = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password}'
98
+ # self.connection = pyodbc.connect(conn_str)
99
+ #
100
+ # elif self.db_type == DatabaseType.MYSQL:
101
+ # if pymysql is None:
102
+ # raise ImportError("请安装pymysql库: pip install pymysql")
103
+ #
104
+ # host = kwargs.get('host', 'localhost')
105
+ # database = kwargs.get('database', 'mysql')
106
+ # user = kwargs.get('user', 'root')
107
+ # password = kwargs.get('password', '')
108
+ # port = kwargs.get('port', 3306)
109
+ #
110
+ # self.connection = pymysql.connect(
111
+ # host=host, user=user, password=password,
112
+ # database=database, port=port, charset='utf8mb4'
113
+ # )
114
+ #
115
+ # elif self.db_type == DatabaseType.ORACLE:
116
+ # if cx_Oracle is None:
117
+ # raise ImportError("请安装cx_Oracle库: pip install cx_Oracle")
118
+ #
119
+ # dsn = kwargs.get('dsn')
120
+ # user = kwargs.get('user')
121
+ # password = kwargs.get('password')
122
+ #
123
+ # self.connection = cx_Oracle.connect(user, password, dsn)
124
+ #
125
+ # elif self.db_type == DatabaseType.SQLITE:
126
+ # if sqlite3 is None:
127
+ # raise ImportError("sqlite3是Python标准库的一部分,但您的环境似乎不支持")
128
+ #
129
+ # database = kwargs.get('database', ':memory:')
130
+ # self.connection = sqlite3.connect(database)
131
+ #
132
+ # self.logger.info(f"成功连接到{self.db_type.value}数据库")
133
+ #
134
+ # except Exception as e:
135
+ # self.logger.error(f"数据库连接失败: {str(e)}")
136
+ # raise
137
+ #
138
+ # def execute(self, sql: str, params: Union[Tuple, List, Dict] = None) -> int:
139
+ # """
140
+ # 执行SQL语句(INSERT, UPDATE, DELETE等)
141
+ #
142
+ # Args:
143
+ # sql: SQL语句
144
+ # params: 参数
145
+ #
146
+ # Returns:
147
+ # 影响的行数
148
+ # """
149
+ # try:
150
+ # with self.connection.cursor() as cursor:
151
+ # if params:
152
+ # cursor.execute(sql, params)
153
+ # else:
154
+ # cursor.execute(sql)
155
+ #
156
+ # # 对于SQLite,需要特殊处理rowcount
157
+ # if self.db_type == DatabaseType.SQLITE:
158
+ # if sql.strip().lower().startswith(('insert', 'update', 'delete')):
159
+ # self.connection.commit()
160
+ #
161
+ # rowcount = cursor.rowcount
162
+ # self.connection.commit()
163
+ # return rowcount
164
+ #
165
+ # except Exception as e:
166
+ # self.connection.rollback()
167
+ # self.logger.error(f"执行SQL失败: {sql}, 错误: {str(e)}")
168
+ # raise
169
+ #
170
+ # def executemany(self, sql: str, params_list: List[Union[Tuple, List, Dict]]) -> int:
171
+ # """
172
+ # 批量执行SQL语句
173
+ #
174
+ # Args:
175
+ # sql: SQL语句
176
+ # params_list: 参数列表
177
+ #
178
+ # Returns:
179
+ # 影响的行数
180
+ # """
181
+ # try:
182
+ # with self.connection.cursor() as cursor:
183
+ # cursor.executemany(sql, params_list)
184
+ # rowcount = cursor.rowcount
185
+ # self.connection.commit()
186
+ # return rowcount
187
+ #
188
+ # except Exception as e:
189
+ # self.connection.rollback()
190
+ # self.logger.error(f"批量执行SQL失败: {sql}, 错误: {str(e)}")
191
+ # raise
192
+ #
193
+ # def query(self, sql: str, params: Union[Tuple, List, Dict] = None) -> List[Tuple]:
194
+ # """
195
+ # 执行查询语句
196
+ #
197
+ # Args:
198
+ # sql: SQL查询语句
199
+ # params: 参数
200
+ #
201
+ # Returns:
202
+ # 查询结果列表
203
+ # """
204
+ # try:
205
+ # with self.connection.cursor() as cursor:
206
+ # if params:
207
+ # cursor.execute(sql, params)
208
+ # else:
209
+ # cursor.execute(sql)
210
+ #
211
+ # return cursor.fetchall()
212
+ #
213
+ # except Exception as e:
214
+ # self.logger.error(f"查询失败: {sql}, 错误: {str(e)}")
215
+ # raise
216
+ #
217
+ # def query_one(self, sql: str, params: Union[Tuple, List, Dict] = None) -> Optional[Tuple]:
218
+ # """
219
+ # 执行查询语句,返回第一条结果
220
+ #
221
+ # Args:
222
+ # sql: SQL查询语句
223
+ # params: 参数
224
+ #
225
+ # Returns:
226
+ # 第一条查询结果或None
227
+ # """
228
+ # try:
229
+ # with self.connection.cursor() as cursor:
230
+ # if params:
231
+ # cursor.execute(sql, params)
232
+ # else:
233
+ # cursor.execute(sql)
234
+ #
235
+ # return cursor.fetchone()
236
+ #
237
+ # except Exception as e:
238
+ # self.logger.error(f"查询失败: {sql}, 错误: {str(e)}")
239
+ # raise
240
+ #
241
+ # def query_to_dataframe(self, sql: str, params: Union[Tuple, List, Dict] = None) -> pd.DataFrame:
242
+ # """
243
+ # 执行查询语句,返回Pandas DataFrame
244
+ #
245
+ # Args:
246
+ # sql: SQL查询语句
247
+ # params: 参数
248
+ #
249
+ # Returns:
250
+ # Pandas DataFrame
251
+ # """
252
+ # try:
253
+ # return pd.read_sql_query(sql, self.connection, params=params)
254
+ # except Exception as e:
255
+ # self.logger.error(f"查询到DataFrame失败: {sql}, 错误: {str(e)}")
256
+ # raise
257
+ #
258
+ # def table_exists(self, table_name: str) -> bool:
259
+ # """
260
+ # 检查表是否存在
261
+ #
262
+ # Args:
263
+ # table_name: 表名
264
+ #
265
+ # Returns:
266
+ # 是否存在
267
+ # """
268
+ # try:
269
+ # if self.db_type == DatabaseType.SQLSERVER:
270
+ # sql = """
271
+ # SELECT COUNT(*)
272
+ # FROM INFORMATION_SCHEMA.TABLES
273
+ # WHERE TABLE_NAME = ?
274
+ # """
275
+ # elif self.db_type == DatabaseType.MYSQL:
276
+ # sql = """
277
+ # SELECT COUNT(*)
278
+ # FROM INFORMATION_SCHEMA.TABLES
279
+ # WHERE TABLE_NAME = %s AND TABLE_SCHEMA = DATABASE()
280
+ # """
281
+ # elif self.db_type == DatabaseType.ORACLE:
282
+ # sql = """
283
+ # SELECT COUNT(*)
284
+ # FROM USER_TABLES
285
+ # WHERE TABLE_NAME = UPPER(:table_name)
286
+ # """
287
+ # elif self.db_type == DatabaseType.SQLITE:
288
+ # sql = """
289
+ # SELECT COUNT(*)
290
+ # FROM sqlite_master
291
+ # WHERE type='table' AND name=?
292
+ # """
293
+ #
294
+ # result = self.query_one(sql, (table_name,))
295
+ # return result[0] > 0 if result else False
296
+ #
297
+ # except Exception as e:
298
+ # self.logger.error(f"检查表是否存在失败: {table_name}, 错误: {str(e)}")
299
+ # raise
300
+ #
301
+ # def get_table_columns(self, table_name: str) -> List[str]:
302
+ # """
303
+ # 获取表的列名列表
304
+ #
305
+ # Args:
306
+ # table_name: 表名
307
+ #
308
+ # Returns:
309
+ # 列名列表
310
+ # """
311
+ # try:
312
+ # # 使用Pandas获取表结构信息
313
+ # df = pd.read_sql_query(f"SELECT * FROM {table_name} WHERE 1=0", self.connection)
314
+ # return df.columns.tolist()
315
+ # except Exception as e:
316
+ # self.logger.error(f"获取表列名失败: {table_name}, 错误: {str(e)}")
317
+ # raise
318
+ #
319
+ # def close(self) -> None:
320
+ # """关闭数据库连接"""
321
+ # if self.connection:
322
+ # self.connection.close()
323
+ # self.connection = None
324
+ # self.logger.info("数据库连接已关闭")
325
+ #
326
+ # def __enter__(self):
327
+ # """支持上下文管理器"""
328
+ # return self
329
+ #
330
+ # def __exit__(self, exc_type, exc_val, exc_tb):
331
+ # """退出上下文时自动关闭连接"""
332
+ # self.close()
333
+ #
334
+ #
335
+ # # 使用示例
336
+ # if __name__ == "__main__":
337
+ # # 设置日志
338
+ # logging.basicConfig(level=logging.INFO)
339
+ #
340
+ # # SQLite示例
341
+ # try:
342
+ # with DbUtil('sqlite', database=':memory:') as db:
343
+ # # 创建表
344
+ # db.execute("""
345
+ # CREATE TABLE users (
346
+ # id INTEGER PRIMARY KEY AUTOINCREMENT,
347
+ # name TEXT NOT NULL,
348
+ # email TEXT NOT NULL UNIQUE,
349
+ # created_at DATETIME DEFAULT CURRENT_TIMESTAMP
350
+ # )
351
+ # """)
352
+ #
353
+ # # 插入数据
354
+ # db.execute(
355
+ # "INSERT INTO users (name, email) VALUES (?, ?)",
356
+ # ("张三", "zhangsan@example.com")
357
+ # )
358
+ #
359
+ # # 批量插入
360
+ # users = [
361
+ # ("李四", "lisi@example.com"),
362
+ # ("王五", "wangwu@example.com")
363
+ # ]
364
+ # db.executemany(
365
+ # "INSERT INTO users (name, email) VALUES (?, ?)",
366
+ # users
367
+ # )
368
+ #
369
+ # # 查询数据
370
+ # results = db.query("SELECT * FROM users")
371
+ # print("所有用户:")
372
+ # for row in results:
373
+ # print(row)
374
+ #
375
+ # # 查询到DataFrame
376
+ # df = db.query_to_dataframe("SELECT * FROM users")
377
+ # print("\nDataFrame格式:")
378
+ # print(df)
379
+ #
380
+ # # 检查表是否存在
381
+ # exists = db.table_exists("users")
382
+ # print(f"\n用户表是否存在: {exists}")
383
+ #
384
+ # # 获取列名
385
+ # columns = db.get_table_columns("users")
386
+ # print(f"用户表的列: {columns}")
387
+ #
388
+ # except Exception as e:
389
+ # print(f"错误: {e}")