Python方向 1、创建ConDataBase类,将连接数据库的程序代码放入其中,并改造上个实验中的数据库连接,使所有有数据库连接的地方都改成调用ConDataBase类,来完成数据库的连接。
时间: 2024-10-19 19:13:20 浏览: 22
在Python中,为了创建一个名为`ConDataBase`的类用于管理数据库连接,你可以这样做:
```python
import sqlite3
class ConDataBase:
def __init__(self, db_name):
self.conn = None
self.db_name = db_name
def connect(self):
try:
self.conn = sqlite3.connect(self.db_name)
print(f"Connected to {self.db_name} successfully.")
except sqlite3.Error as e:
print(f"Error occurred: {e}")
def execute_query(self, query):
cursor = self.conn.cursor()
try:
cursor.execute(query)
self.conn.commit()
except sqlite3.Error as e:
print(f"Error executing query: {e}")
return cursor.fetchall()
def close_connection(self):
if self.conn:
self.conn.close()
print("Connection closed.")
# 使用示例
db_conn = ConDataBase('my_database.db')
db_conn.connect() # 连接到数据库
query = "SELECT * FROM table;"
data = db_conn.execute_query(query)
db_conn.close_connection() # 关闭连接
阅读全文