python连接sqlite3工具类
import sqlite3
class SQLiteHelper:
def __init__(self, db_name):
self.connection = None
self.cursor = None
self.db_name = db_name
def connect(self):
"""连接到SQLite数据库"""
self.connection = sqlite3.connect(self.db_name)
self.cursor = self.connection.cursor()
def execute_query(self, query):
"""执行查询操作"""
self.connect()
self.cursor.execute(query)
return self.cursor.fetchall()
def execute_multiple_query(self, queries):
"""执行多个查询操作"""
self.connect()
for query in queries:
self.cursor.execute(query)
self.connection.commit()
def close(self):
"""关闭数据库连接"""
if self.connection:
self.connection.close()
# 使用示例
db_name = 'example.db'
helper = SQLiteHelper(db_name)
query = "SELECT * FROM some_table;"
results = helper.execute_query(query)
print(results)
queries = [
"INSERT INTO some_table (column1, column2) VALUES (value1, value2);",
"UPDATE some_table SET column1 = value1 WHERE id = 1;"
]
helper.execute_multiple_query(queries)
helper.close()
这个代码示例展示了如何创建一个简单的SQLite数据库助手类,它提供了连接、查询执行和关闭数据库连接的基本功能。这个类可以用来执行SQLite数据库的常规操作,使得数据库交互变得更加简单和标准化。
评论已关闭