封装一个mysql增删改查的方法
时间: 2023-12-26 19:51:42 浏览: 99
[示例][PHP]MySQL增删改查PHP类.zip
这是一个基于Python的MySQL增删改查方法的示例:
```python
import mysql.connector
# 创建数据库连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 定义查询方法
def select_data(table, columns, condition=None):
mycursor = mydb.cursor()
if condition:
sql = "SELECT {} FROM {} WHERE {}".format(columns, table, condition)
else:
sql = "SELECT {} FROM {}".format(columns, table)
mycursor.execute(sql)
result = mycursor.fetchall()
return result
# 定义插入方法
def insert_data(table, columns, values):
mycursor = mydb.cursor()
sql = "INSERT INTO {} ({}) VALUES ({})".format(table, columns, values)
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
# 定义更新方法
def update_data(table, set_values, condition):
mycursor = mydb.cursor()
sql = "UPDATE {} SET {} WHERE {}".format(table, set_values, condition)
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected.")
# 定义删除方法
def delete_data(table, condition):
mycursor = mydb.cursor()
sql = "DELETE FROM {} WHERE {}".format(table, condition)
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted.")
```
使用示例:
```python
# 查询数据
result = select_data("customers", "*", "name = 'John'")
for row in result:
print(row)
# 插入数据
insert_data("customers", "name, address", "'John', 'Highway 21'")
# 更新数据
update_data("customers", "address = 'Park Lane 38'", "name = 'John'")
# 删除数据
delete_data("customers", "address = 'Highway 21'")
```
阅读全文