pymysql的使用

        1.查询数据

                     八个步骤: 1.导包:import pymysql

                                        2.连接mysql数据库服务:conne = pymysql.Connect()

                                        3.创建游标对象:cur = conne.cursor()

                                        4.编写sql语句:sql = 'select * from 万能表;'

                                        5.使用游标对象调用sql语句:cur.execute(sql)

                                        6.获取查询结果集,返回的是列表:result = cur.fetchall()

                                        7.关闭游标对象:cur.close()

                                        8.关闭连接:conne.close()

        例子:

# 使用步骤
# 1.导包
import pymysql
# 2.连接mysql数据库服务
try:
    conne = pymysql.Connect(
        user='root',
        password='Z20020803',
        # host='192.168.68.130',
        host = 'localhost',
        database='itcast',
        port=3306,
        charset='utf8'
    )
    # 3.创建游标对象
    cor = conne.cursor()
    # 4.编写SQL语句
    sql = 'select * from 万能表;'
    # 5.使用游标对象调用SQL语句
    cor.execute(sql)
    # 6.获取查询结果集,返回的是列表
    result = cor.fetchall()
    print(result)
    # 7.关闭游标对象
    cor.close()
    # 8.关闭连接
    conne.close()
except Exception as e:
    print(e)

        2. 增加、修改和删除数据

                步骤和查询一样,但是要增加一个提交操作:conne.commit()

        例子:

try:
    # 1.导包
    import pymysql
    # 2.连接mysql数据库服务
    conne = pymysql.Connect(
        user = 'root',
        host = 'localhost',
        port = 3306,
        password = 'Z20020803',
        database = 'itcast',
        charset = 'utf8'
    )
    # 3.创建游标对象
    cur = conne.cursor()
    # 4.编写sql语句
    # 增加数据
    # 方式一
    insert_sql = "insert into 万能表 (姓名, 性别, 年龄) values ('lly', '女', 20);"
    # 方式二
    insert_sql2 = "insert into 万能表 (姓名, 性别, 年龄) values (%s, %s, %s);"
    # 删除数据
    delete_sql = "delete from 万能表 where 姓名 is null;"
    # 更改数据
    update_del = "update 万能表 set 性别 = '女' where 姓名 = '张三';"
    # 5.用游标对象调用sql语句
    # cur.execute(insert_sql)  # 增加数据语句调用
    cur.execute(insert_sql2, ['曾浩', '男', 20])    # 待用增加函数,传递的参数必须是列表
    # cur.execute(delete_sql)  # 删除数据语句调用
    # cur.execute(update_del)  # 更改数据
    # 6.提交数据,只有提交,数据库才会记录数据
    conne.commit()
except Exception as e:
    print(e)
    # 数据回滚
    conne.rollback()
# 7.关闭游标对象
cur.close()
# 8.关闭连接服务
cur.close()

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱笑的蛐蛐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值