pymysql常用方法

发布时间 2023-08-26 06:17:46作者: linux星

pymysql是一个Python第三方库,用于连接和操作MySQL数据库。以下是pymysql的基本使用方法:

 

安装pymysql库:

 

 

pip install pymysql

 

 

连接到MySQL数据库:

 

 

import pymysql

 

# 创建连接

conn = pymysql.connect(host='localhost', user='root', password='your_password', database='your_database', charset='utf8')

 

# 创建游标

cursor = conn.cursor()

 

 

执行SQL语句:

 

 

# 编写SQL语句

sql = "SELECT * FROM your_table"

 

# 执行SQL语句

cursor.execute(sql)

 

# 获取查询结果

result = cursor.fetchall()

 

# 打印查询结果

for row in result:

    print(row)

 

# 关闭游标

cursor.close()

 

# 关闭连接

conn.close()

 

 

插入、更新和删除数据:

 

 

# 编写插入、更新或删除的SQL语句

sql_insert = "INSERT INTO your_table (column1, column2) VALUES ('value1', 'value2')"

sql_update = "UPDATE your_table SET column1='new_value1' WHERE condition"

sql_delete = "DELETE FROM your_table WHERE condition"

 

# 执行SQL语句

cursor.execute(sql_insert)

cursor.execute(sql_update)

cursor.execute(sql_delete)

 

# 提交事务

conn.commit()

 

# 关闭游标

cursor.close()

 

# 关闭连接

conn.close()

 

 

注意:在实际使用中,需要将 your_password 、 your_database 、 your_table 、 column1 、 column2 等替换为实际的值。