Python之数据库编程

目录

一、MySQL数据库的使用

 数据库相关操作

二、数据库增删改查 

 增加

 修改

删除

三、数据库标准写法


一、MySQL数据库的使用

 

 建表

 CREATE TABLE py_student(
id INTEGER primary key auto_increment,
name INTEGER not null,
gender varchar(11) default '男' ,
birthday datetime
)

 安装PYMYSQL安装包   ---打开 setting设置

 

 

 

 

 数据库连接mysql (填写用户名、密码即可)

 

 

 数据库相关操作

 1.查询

from pymysql import connect
# 直接导入connect

# 建立连接
con=connect(user="root",password="123456",host="localhost",database="mysql")
# 拿到游标
cur=con.cursor()
# 执行查询
cur.execute("select  * from py_student")
# 处理结果集
# print(cur.fetchone())
print(cur.fetchall()) # 查询全部
# print(cur.fetchmany(3))

 单个查询

# 按条件查询
cur.execute("select * from py_student where  id = %s",(1))

 

 

查询多个

# cur.execute("select * from py_student where id =%s and name like %s",(3,"%小%")) print(cur.fetchall())

  分页

 分页
cur.execute("select * from py_student  limit 1,2")
print(cur.fetchall())

 


 

二、数据库增删改查 

 增加

# 增删改查
from pymysql import connect
# 直接导入connect

# 建立连接
con=connect(user="root",password="123456",host="localhost",database="mysql")
# 拿到游标
cur=con.cursor()
cur.execute("""insert into py_student value (4,'嘻哈UN个','女','2002-2-2')""")

此时会执行失效:原因是没有提交事务:con.commit() # 提交事务

 

 修改

修改
cur.execute("""update py_student set name=%s  where id=%s""",('dog','4'))

con.commit() # 提交事务

 

删除

# 删除
cur.execute("""delete from py_student where id=%s""",('4'))
con.commit() # 提交事务

 

三、数据库标准写法

 由于commit操作(con.commit() # 提交事务)如果收到阻碍之间有错误,则不能正常执行删改操作,新增正常执行

# 标准写法 --->验证同时新增和修改数据成功
try:
    cur.execute("""insert into py_student values(8,'威武','女','2002-2-2')""") 
    cur.execute("""update py_student set name=%s  where id=%s""",('NEWdog','6'))
except Exception as e:
    print(e)
    con.rollback() #回滚操作

else:
    con.commit()
finally:
    cur.close() #关闭资源
    con.close()

 


  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值