chatGPT答: |
8v6.cn |
下面是一个简单的示例,演示了如何使用Python调用MySQL数据库,并使用类和对象的形式封装增删改查操作:
```python
import mysql.connector
class MySQLDatabase:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
self.connection = mysql.connector.connect(
host=self.host,
user=self.user,
password=self.password,
database=self.database
)
def execute_query(self, query):
cursor = self.connection.cursor()
cursor.execute(query)
def fetch_data(self, query):
cursor = self.connection.cursor()
cursor.execute(query)
return cursor.fetchall()
def insert_data(self, table_name, data):
columns = ', '.join(data.keys())
values_template = ', '.join(['%s'] * len(data))
query= f"INSERT INTO {table_name} ({columns}) VALUES ({values_template})"
values= tuple(data.values())
cursor= connection.cursor()
cursor.execute(query ,values)
connection.commit()
print("Data inserted successfully")
def update_data(self ,table_name ,data ,condition):
set_values=[]
for key,value in data.items():
set_values.append(f"{key}= '{value}'")
set_values_string=', '.join(set_values)
condition_string=[]
for key,value in condition.items():
condition_string.append(f"{key}= '{value}'")
condition_string=' AND '.join(condition_string)
query=f"UPDATE {table_name} SET {set_values_string} WHERE {condition_string}"
cursor=connection.cursor()
cursor.execute(query)
connection.commit()
print("Data updated successfully")
def delete_data(self ,table_name ,condition):
condition_strings=[]
for key,value in conditions.items():
conditions_strings.append(f"{key}= '{value}'")
conditions_strings=' AND ' . join(conditions_strings)
query=f"DELETE FROM{table_name} WHERE{conditions_strings}"
cursor=connection.cursor()
cursor.execute(query)
connection.commit()
print("Data deleted successfully")
# 使用示例
# 创建数据库连接对象
db_connection=MySQLDatabase('localhost','root','password','test_db')
# 插入数据
data={'name':'John' ,'age':25,'city':'New York'}
db_connection.insert_data('users',data)
# 更新数据
update_data={'age':30}
condition={'name':'John'}
db_connection.update_date('users',update_date.condition)
# 删除数据
delete_condition={'name':'John'}
db_connection.delete_date('users',delete_condition)
```
在上面的示例中,我们创建了一个名为`MySQLDatabase`的类,它包含了与MySQL数据库交互所需的方法。我们可以实例化这个类,并使用其提供的接口来执行增删改查操作。
值得注意的是,在实际开发中,需要考虑异常处理、安全性等因素。此外,还可以根据具体需求扩展该类,添加更多功能和接口。
|