Pymysql的使用
一、使用MySQL workbench建立数据库、表
创建spider数据库
1 2 3 | drop database spider; create database spider; ALTER DATABASE spider CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; |
创建users表
1 2 3 4 5 6 7 8 9 | use spider; drop table if exists users; 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=utf8mb4 collate =utf8mb4_bin auto_increment=1; |
二、安装pymysql
安装pymysql
三、使用pymysql
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 | import pymysql.cursors #Connection to the database connection = pymysql.connect( host = '127.0.0.1' , port = 3306 , user = 'root' , passwd = '123456' , db = 'spider' , charset = 'utf8' , 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() |
运行结果:
执行了三次,所以有三条数据
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)