python针对mysql数据库的连接、查询、更新、删除操作示例
本文实例讲述了python针对mysql数据库的连接、查询、更新、删除操作。分享给大家供大家参考,具体如下:
连接
一代码
importpymysql #打开数据库连接 db=pymysql.connect("localhost","root","root","db_test01") #使用cursor()方法创建一个游标对象cursor cursor=db.cursor() #使用execute()方法执行SQL查询 cursor.execute("SELECTVERSION()") #使用fetchone()方法获取单条数据. data=cursor.fetchone() print("Databaseversion:%s"%data) #关闭数据库连接 db.close()
二运行结果
py=======
Databaseversion:5.7.10-log
查询
一代码
importpymysql #打开数据库连接 db=pymysql.connect("localhost","root","root","db_test01") #使用cursor()方法获取操作游标 cursor=db.cursor() #SQL查询语句 sql="SELECT*FROMEMPLOYEE\ WHEREINCOME>'%d'"%(1000) try: #执行SQL语句 cursor.execute(sql) #获取所有记录列表 results=cursor.fetchall() forrowinresults: fname=row[0] lname=row[1] age=row[2] sex=row[3] income=row[4] #打印结果 print("fname=%s,lname=%s,age=%d,sex=%s,income=%d"%\ (fname,lname,age,sex,income)) except: print("Error:unabletofetchdata") #关闭数据库连接 db.close()
二运行结果
fname=Mac,lname=Mohan,age=20,sex=M,income=2000
更新
一代码
importpymysql #打开数据库连接 db=pymysql.connect("localhost","root","root","db_test01") #使用cursor()方法获取操作游标 cursor=db.cursor() #SQL更新语句 sql="UPDATEEMPLOYEESETAGE=AGE+1WHERESEX='%c'"%('M') try: #执行SQL语句 cursor.execute(sql) #提交到数据库执行 db.commit() print("updateOK") except: #发生错误时回滚 db.rollback() #关闭数据库连接 db.close()
二运行结果
updateOK
删除
一代码
importpymysql #打开数据库连接 db=pymysql.connect("localhost","root","root","db_test01") #使用cursor()方法获取操作游标 cursor=db.cursor() #SQL删除语句 sql="DELETEFROMEMPLOYEEWHEREAGE>'%d'"%(20) try: #执行SQL语句 cursor.execute(sql) #提交修改 db.commit() print("deleteOK") except: #发生错误时回滚 db.rollback() #关闭连接 db.close()
二运行结果
deleteOK
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。