![图片[1]-python怎么操作mysql-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5dc52790e304d297.jpg)
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x,而MySQLdb不支持3.x版本。
本文测试python版本:3.6。mysql版本:5.6.24
1.通过 pip 安装 pymysql
进入cmd,输入:
pipinstallpymysql
按回车键,等待安装完成。
	
2.测试连接
importpymysql#导入pymysql,如果编译未出错,即表示pymysql安装成功
3.pymysql操作
表结构如下:
	
3.1查询操作
importpymysql#导入pymysql
#打开数据库连接
db=pymysql.connect(host="localhost",user="root",
password="123456",db="test",port=3307)
#使用cursor()方法获取操作游标
cur=db.cursor()
#1.查询操作
#编写sql查询语句user对应我的表名
sql="select*fromuser"
try:
cur.execute(sql)#执行sql语句
results=cur.fetchall()#获取查询的所有记录
print("id","name","password")
#遍历结果
forrowinresults:
id=row[0]
name=row[1]
password=row[2]
print(id,name,password)
exceptExceptionase:
raisee
finally:
db.close()#关闭连接
3.2插入操作
importpymysql #2.插入操作 db=pymysql.connect(host="localhost",user="root", password="123456",db="test",port=3307) #使用cursor()方法获取操作游标 cur=db.cursor() sql_insert="""insertintouser(id,username,password)values(4,'liu','1234')""" try: cur.execute(sql_insert) #提交 db.commit() exceptExceptionase: #错误回滚 db.rollback() finally: db.close()
3.3更新操作
#3.更新操作
db=pymysql.connect(host="localhost",user="root",
password="123456",db="test",port=3307)
#使用cursor()方法获取操作游标
cur=db.cursor()
sql_update="updateusersetusername='%s'whereid=%d"
try:
cur.execute(sql_update%("xiongda",3))#像sql语句传递参数
#提交
db.commit()
exceptExceptionase:
#错误回滚
db.rollback()
finally:
db.close()
3.4删除操作
importpymysql #4.删除操作 db=pymysql.connect(host="localhost",user="root", password="123456",db="test",port=3307) #使用cursor()方法获取操作游标 cur=db.cursor() sql_delete="deletefromuserwhereid=%d" try: cur.execute(sql_delete%(3))#像sql语句传递参数 #提交 db.commit() exceptExceptionase: #错误回滚 db.rollback() finally: db.close()原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
    


















































 
        

暂无评论内容