以类的形式写Python的pymysqlDB
时间: 2024-09-23 14:13:03 浏览: 33
在Python中,我们可以使用`pymysql`库来连接MySQL数据库,并将其封装成类的形式以便于管理和复用。以下是一个简单的例子,展示了如何创建一个名为`MysqlDB`的类,用于处理数据库操作:
```python
import pymysql
class MysqlDB:
def __init__(self, host='localhost', user='your_username', password='your_password', db='your_database'):
self.conn = None
self.connect_params = {
'host': host,
'user': user,
'password': password,
'db': db
}
def connect(self):
self.conn = pymysql.connect(**self.connect_params)
return self.conn
def close(self):
if self.conn is not None:
self.conn.close()
def execute_query(self, query):
try:
with self.conn.cursor() as cursor:
cursor.execute(query)
result = cursor.fetchall()
return result
except Exception as e:
print(f"Error executing query: {e}")
def insert_data(self, table_name, data_dict):
try:
keys, values = zip(*data_dict.items())
placeholders = ', '.join(['%s'] * len(keys))
query = f"INSERT INTO {table_name} ({', '.join(keys)}) VALUES ({placeholders})"
with self.conn.cursor() as cursor:
cursor.execute(query, values)
self.conn.commit()
except Exception as e:
print(f"Error inserting data: {e}")
# 使用示例
db = MysqlDB(host="127.0.0.1", user="root", password="password", db="test_db")
try:
db.connect()
# 执行查询
results = db.execute_query("SELECT * FROM users")
for row in results:
print(row)
# 插入数据
db.insert_data("users", {"name": "John Doe", "age": 30})
finally:
db.close()
阅读全文