python操作崖山数据库进行增删改查
时间: 2024-10-10 21:16:19 浏览: 59
在Python中操作MySQL(也称为MariaDB,因为它们兼容)这样的关系型数据库,最常用的是使用像`pymysql`或者`mysql-connector-python`这样的库。对于崖山数据库(实际上可能是MySQL误拼,这里假设你是指MySQL),下面是一个基本的例子,展示了如何使用Python进行增删改查操作:
```python
import pymysql
# 连接到数据库
def connect_db(host, user, password, db):
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor # 使用字典形式的游标
)
return connection
# 关闭连接
def close_conn(connection):
connection.close()
# 插入数据
def insert_data(conn, table_name, columns, values):
with conn.cursor() as cursor:
sql = f"INSERT INTO {table_name} ({', '.join(columns)}) VALUES ({', '.join(['%s'] * len(values))})"
cursor.execute(sql, values)
conn.commit()
# 查询数据
def select_data(conn, table_name, conditions=None, fields=None):
with conn.cursor() as cursor:
if conditions:
sql = f"SELECT {(', '.join(fields))} FROM {table_name} WHERE {conditions}"
else:
sql = f"SELECT {(', '.join(fields))} FROM {table_name}"
cursor.execute(sql)
return cursor.fetchall()
# 更新数据
def update_data(conn, table_name, set_values, where_conditions):
with conn.cursor() as cursor:
sql = f"UPDATE {table_name} SET {set_values} WHERE {where_conditions}"
cursor.execute(sql)
conn.commit()
# 删除数据
def delete_data(conn, table_name, where_conditions):
with conn.cursor() as cursor:
sql = f"DELETE FROM {table_name} WHERE {where_conditions}"
cursor.execute(sql)
conn.commit()
# 示例用法
connection = connect_db('localhost', 'username', 'password', 'database_name')
try:
# 插入一条记录
insert_data(connection, 'users', ['name', 'email'], ('John Doe', 'john.doe@example.com'))
# 查询所有用户
users = select_data(connection, 'users')
# 更新某个用户的邮箱
update_data(connection, 'users', "email='%s'", "name='John Doe'")
# 删除邮件地址为'john.doe@example.com'的用户
delete_data(connection, 'users', "email='john.doe@example.com'")
finally:
close_conn(connection)
```
阅读全文