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

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

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值