pymysql使用说明
2018年2月21日前期准备
1 2 |
#链接数据库 mysql -uroot -p |
1 2 |
#创建一个新的数据库 CREATE DATABASE db |
1 2 3 4 5 6 7 8 |
#创建一个新的数据表 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 ; |
编写代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import pymysql.cursors # 链接数据库 connection = pymysql.connect(host='localhost', user='root', password='', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: #取别名 with connection.cursor() as cursor: # 创建一条数据 sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('webmaster@python.org', 'very-secret')) #连接默认情况下不是自动提交。所以你必须承诺保存 connection.commit() with connection.cursor() as cursor: # 查询一条数据 sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('webmaster@python.org',)) result = cursor.fetchone() print(result) finally: #关闭链接 connection.close() |