0
点赞
收藏
分享

微信扫一扫

PyMySQL增删查改CRUD

菜头粿子园 2022-07-12 阅读 105


PyMySQL增删查改的例子:

表结构:

CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`password` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)

try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

# 字典方式
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%(email)s, %(password)s)"
cursor.execute(sql, {'email':'webmaster@python.org', 'password':'very-secret'})

# 获取插入id
last_id = curs.lastrowid

# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()

with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()

打印结果:

{'password': 'very-secret', 'id': 1}

参考:https://pymysql.readthedocs.io/en/latest/user/examples.html


举报

相关推荐

0 条评论