python+pymysql对数据库进行增、删、改、查操作
要使用Python和pymysql对数据库进行增、删、改、查操作,首先需要安装pymysql模块,可以使用pip安装:
pip install pymysql
以下是使用pymysql进行基本操作的示例代码:
import pymysql
# 连接数据库
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
database='your_database',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# 创建表
# sql = "CREATE TABLE `users` (`id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
# cursor.execute(sql)
# 插入数据
# sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
# cursor.execute(sql, ('webmaster@example.com', 'very-secret'))
# 查询数据
sql = "SELECT * FROM `users`"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
# 更新数据
# sql = "UPDATE `users` SET `password` = %s WHERE `email` = %s"
# cursor.execute(sql, ('new-password', 'webmaster@example.com'))
# 删除数据
# sql = "DELETE FROM `users` WHERE `email` = %s"
# cursor.execute(sql, ('webmaster@example.com',))
finally:
connection.close()
请确保替换连接参数中的localhost
, your_username
, your_password
, 和 your_database
为你的数据库实际信息。同时,根据需要取消对注释,以执行创建表、插入数据、查询数据、更新数据或删除数据的操作。
评论已关闭