请写出10个python操作mysql的函数,每个函数要能独立运行,我是个小白,请写出每行的详细注释好让我明白这行代码的功能
时间: 2024-02-27 19:53:49 浏览: 51
python操作mysql代码
当然可以!以下是10个Python操作MySQL的函数,每个函数都有注释说明:
```python
import mysql.connector
# 连接MySQL数据库
def connect_to_mysql():
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
return mydb
# 创建数据库
def create_database(database_name):
mydb = connect_to_mysql()
cursor = mydb.cursor()
cursor.execute("CREATE DATABASE " + database_name)
# 查询所有数据库
def show_databases():
mydb = connect_to_mysql()
cursor = mydb.cursor()
cursor.execute("SHOW DATABASES")
for db in cursor:
print(db)
# 创建表
def create_table(table_name, columns):
mydb = connect_to_mysql()
cursor = mydb.cursor()
cursor.execute("CREATE TABLE " + table_name + " (" + columns + ")")
# 插入数据
def insert_data(table_name, values):
mydb = connect_to_mysql()
cursor = mydb.cursor()
cursor.execute("INSERT INTO " + table_name + " VALUES (" + values + ")")
mydb.commit()
# 查询数据
def select_data(table_name, columns):
mydb = connect_to_mysql()
cursor = mydb.cursor()
cursor.execute("SELECT " + columns + " FROM " + table_name)
result = cursor.fetchall()
for row in result:
print(row)
# 更新数据
def update_data(table_name, set_value, where_condition):
mydb = connect_to_mysql()
cursor = mydb.cursor()
cursor.execute("UPDATE " + table_name + " SET " + set_value + " WHERE " + where_condition)
mydb.commit()
# 删除数据
def delete_data(table_name, where_condition):
mydb = connect_to_mysql()
cursor = mydb.cursor()
cursor.execute("DELETE FROM " + table_name + " WHERE " + where_condition)
mydb.commit()
# 删除表
def drop_table(table_name):
mydb = connect_to_mysql()
cursor = mydb.cursor()
cursor.execute("DROP TABLE " + table_name)
# 关闭MySQL连接
def close_mysql():
mydb = connect_to_mysql()
mydb.close()
```
注意,以上代码只是示例,不一定适用于所有情况,具体的实现方式需要根据具体的需求进行调整。
阅读全文