python用函数写mysql的增删查改且sql语句用变量和%s代替
时间: 2024-02-16 07:00:23 浏览: 152
python操作mysql数据库实现增删查改
好的,以下是使用变量和%s代替的Python函数来执行MySQL的增删查改操作。请确保您已经安装了Python MySQL数据库驱动程序。
```python
import mysql.connector
# 连接到MySQL数据库
def connect():
cnx = mysql.connector.connect(user='your_username', password='your_password', host='your_host', database='your_database')
return cnx
# 关闭MySQL数据库连接
def close(cnx):
cnx.close()
# 执行MySQL查询
def execute_query(query, values):
cnx = connect()
cursor = cnx.cursor()
cursor.execute(query, values)
result = cursor.fetchall()
cursor.close()
close(cnx)
return result
# 执行MySQL操作(增、删、改)
def execute_operation(query, values):
cnx = connect()
cursor = cnx.cursor()
cursor.execute(query, values)
cnx.commit()
cursor.close()
close(cnx)
# 插入数据
def insert_data(table_name, column_values):
query = "INSERT INTO %s (%s) VALUES (%s)"
columns = ', '.join(column_values.keys())
values = ', '.join(['%s'] * len(column_values))
query = query % (table_name, columns, values)
execute_operation(query, tuple(column_values.values()))
# 修改数据
def update_data(table_name, set_column_values, where_column_values):
query = "UPDATE %s SET %s WHERE %s"
set_columns = ', '.join([f"{col} = %s" for col in set_column_values.keys()])
where_columns = ' AND '.join([f"{col} = %s" for col in where_column_values.keys()])
query = query % (table_name, set_columns, where_columns)
values = tuple(set_column_values.values()) + tuple(where_column_values.values())
execute_operation(query, values)
# 删除数据
def delete_data(table_name, column_values):
query = "DELETE FROM %s WHERE %s"
where_columns = ' AND '.join([f"{col} = %s" for col in column_values.keys()])
query = query % (table_name, where_columns)
values = tuple(column_values.values())
execute_operation(query, values)
# 查询数据
def select_data(table_name, column_values):
query = "SELECT * FROM %s WHERE %s"
where_columns = ' AND '.join([f"{col} = %s" for col in column_values.keys()])
query = query % (table_name, where_columns)
values = tuple(column_values.values())
result = execute_query(query, values)
return result
```
在上面的代码中,您需要将“your_username”、“your_password”、“your_host”和“your_database”替换为您自己的MySQL数据库连接详细信息,将“table_name”替换为您要操作的表的名称。
要插入、更新、删除和查询数据,请使用相应的函数,并将数据作为包含列名和值的字典传递。例如:
```python
# 插入数据
data = {'column1': 'value1', 'column2': 'value2', 'column3': 'value3'}
insert_data('table_name', data)
# 修改数据
set_data = {'column1': 'new_value1', 'column2': 'new_value2'}
where_data = {'column3': 'value3'}
update_data('table_name', set_data, where_data)
# 删除数据
data = {'column1': 'value1'}
delete_data('table_name', data)
# 查询数据
data = {'column1': 'value1'}
result = select_data('table_name', data)
print(result)
```
请注意,这些函数使用%s占位符来代替变量,在执行查询和操作时,使用execute_query和execute_operation函数分别执行。
阅读全文