Python 使用 pymysql 连接Mysql 数据库及简单的增删改查

2019-06-23   阅读:2661   分类:后端    标签: Python

Python数据库及简单的增删改查

image.png

1、查询操作

import pymysql  #导入 pymysql  
  
#打开数据库连接  
db= pymysql.connect(host="localhost",user="root",  
    password="root",db="test",port=3306)  
  
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
  
#1.查询操作  
# 编写sql 查询语句  user 对应我的表名  
sql = "select * from user"  
try:  
    cur.execute(sql)    #执行sql语句  
  
    results = cur.fetchall()    #获取查询的所有记录  
    print("id","urlname","urlhref")  
    #遍历结果  
    for row in results :  
        id = row[0]  
        name = row[1]  
        password = row[2]  
        print(id,urlname,urlhref)  
except Exception as e:  
    raise e  
finally:  
    db.close()  #关闭连接

2、插入操作

import pymysql  
#2.插入操作  
db= pymysql.connect(host="localhost",user="root",  
    password="root",db="test",port=3306)  
  
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
  
sql_insert ="""insert into user(id,urlname,urlhref) values(4,'liu','1234')"""  
  
try:  
    cur.execute(sql_insert)  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close()

3、更新操作

import pymysql  
#3.更新操作  
db= pymysql.connect(host="localhost",user="root",  
    password="root",db="test",port=3306)  
  
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
  
sql_update ="update user set urlname= '%s' where id = %d"  
  
try:  
    cur.execute(sql_update % ("xida",3))  #像sql语句传递参数  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close()

4、删除操作

import pymysql  
#4.删除操作  
db= pymysql.connect(host="localhost",user="root",  
    password="root",db="test",port=3306)  
  
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
  
sql_delete ="delete from user where id = %d"  
  
try:  
    cur.execute(sql_delete % (3))  #像sql语句传递参数  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close()


【腾讯云】 爆款2核2G3M云服务器首年 61元,2核2G4M云服务器新老同享 99元/年,续费同价

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://www.tpxhm.com/adetail/152.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸一
简忆博客壁纸二
简忆博客壁纸三
简忆博客壁纸四
简忆博客壁纸五
简忆博客壁纸六
简忆博客壁纸七
简忆博客壁纸八
头像

简忆博客
勤于学习,乐于分享

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×