pymysql模块是python与mysql进行交互的一个模块。
pymysql模块的安装:
pymysql模块的用法:
import pymysql user=input('user>>:').strip() pwd=input('pwd>>:').strip() conn=pymysql.connect(host='localhost',user='root',password='5257',database='day47',charset='utf8')#连接数据库 cursor=conn.cursor() sql='select * from userinfo where username=%s and password=%s' row=cursor.execute(sql,(user,pwd)) cursor.close() conn.close() if row : print('登录成功') else : print('用户名或密码错误')
运行效果:
pymysql模块查询:
import pymysql conn=pymysql.connect(host='localhost',user='root',password='5257',database='day47', charset='utf8') cursor=conn.cursor() sql='select * from userinfo' row=cursor.execute(sql) print(cursor.fetchone()) #查询一条 print(cursor.fetchmany(2)) #查询指定条数 # print(cursor.fetchall()) #查询全部 cursor.scroll(2,mode='absolute') #绝对路径 print(cursor.fetchone()) cursor.scroll(6,mode='relative') #相对路径 print(cursor.fetchall()) conn.commit() #修改数据库中的文件 cursor.close() conn.close()
pymysql模块增删改:
import pymysql conn=pymysql.connect(host='localhost',user='root',password='5257',database='day47', charset='utf8') cursor=conn.cursor() sql='insert into userinfo(username,password) values(%s,%s)'#sql语句 row=cursor.execute(sql,('fugui','123')) #插入一条记录 row=cursor.executemany(sql,[('moses','123'),('jack','123'),('tom','123')])#插入多条记录 conn.commit() cursor.close() conn.close()