PyMysql是Python中用于连接MySQL数据库的一个第三方库,它实现了MySQL客户端/服务器协议,使得Python程序能够与MySQL服务器进行交互。由于Python
2的mysql-python(又称mysqldb)模块在Python 3上支持不够完善,因此pymysql成为了在Python
3.x环境中一个流行的替代方案。
PyMysql的主要特点和功能:
基本用法步骤:
以下使用PyMysql增删改查Mysql数据库
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
import pymysql
# 连接MySQL数据库
db = pymysql.connect("localhost", "your_username", "your_password", "your_database")
# 创建一个游标对象cursor
cursor = db.cursor()
import pymysql
# 连接MySQL数据库
db = pymysql.connect("localhost", "your_username", "your_password", "your_database")
# 创建一个游标对象cursor
cursor = db.cursor()
try:
sql = "SELECT * FROM users WHERE username = %s"
val = ("test_user",)
cursor.execute(sql, val)
results = cursor.fetchall()
for row in results:
print(f"ID: {row[0]}, Username: {row[1]}, Email: {row[2]}, Password: {row[3]}")
except Exception as e:
print(f"查询数据失败: {e}")
import pymysql
# 连接MySQL数据库
db = pymysql.connect("localhost", "your_username", "your_password", "your_database")
# 创建一个游标对象cursor
cursor = db.cursor()
# 插入数据(INSERT)
try:
sql = "INSERT INTO users (username, email, password) VALUES (%s, %s, %s)"
val = ("test_user", "test@example.com", "test_password")
cursor.execute(sql, val)
db.commit()
print("插入数据成功")
except Exception as e:
db.rollback() # 发生错误时回滚
print(f"插入数据失败: {e}")
import pymysql
# 连接MySQL数据库
db = pymysql.connect("localhost", "your_username", "your_password", "your_database")
# 创建一个游标对象cursor
cursor = db.cursor()
try:
sql = "UPDATE users SET email = %s WHERE username = %s"
val = ("new_email@example.com", "test_user")
cursor.execute(sql, val)
db.commit()
print("更新数据成功")
except Exception as e:
db.rollback()
print(f"更新数据失败: {e}")
import pymysql
# 连接MySQL数据库
db = pymysql.connect("localhost", "your_username", "your_password", "your_database")
# 创建一个游标对象cursor
cursor = db.cursor()
try:
sql = "DELETE FROM users WHERE username = %s"
val = ("test_user",)
cursor.execute(sql, val)
db.commit()
print("删除数据成功")
except Exception as e:
db.rollback()
print(f"删除数据失败: {e}")
cursor.close()
db.close()
请确保将上述代码中的"your_username", “your_password”, "your_database"替换为你的实际数据库用户名、密码和数据库名。