pymysql使用(一)

一、安装

  • Ubuntu

    sudo pip3 install pymysql #安装

    pip3 show pymysql # 查看安装情况

  • Windows

    pip install pymqsql

二、使用

  1. 导包

    import pymysql

  2. 创建和mysql服务器的连接对象

    pymysql.connect(参数列表)

  3. 获取游标对象

    cursor = conn.cursor()

  4. 执行sql语句

    row_count = cursor.execute(sql)

  5. 获取查询结果集

    result = cursor.fetchall()

  6. 将增加和修改操作提交到数据库

    conn.commit()

  7. 回滚数据

    conn.rollback()

  8. 关闭游标对象

    cursor.close()

  9. 关闭连接

    conn.close()

三、实战

实例一

# 对数据单个的增加 修改 删除
# 1. 导包
import pymysql
# 2. 连接mysql服务端
conn = pymysql.connect(user='root',
                        password="",
                        host='127.0.0.1',
                        database='database',
                        port=3306,
                        charset="utf8", )
# 3. 创建游标对象
cur = conn.cursor()
try:
    # 4. 执行sql语句
    # 增加数据
    sql = 'insert into students values (%s,%s,%s,%s,%s)'
    add_data = ['0', '刘德华', '56', '男']
    # 修改数据
    sql = 'update students set name=%s where name="小王"'
    update_data = ['小王吧']
    # 删除数据
    sql = 'delete from students where name=%s'
    del_data = ['李磊']
    # 5. 使用游标对象执行sql
    cur.execute(sql,del_data)

    # 6. 提交操作
    conn.commit()
except Exception as e:
    print(e)
    # 7. 回滚数据
    conn.rollback()
finally:
    # 8. 关闭游标对象
    cur.close()
    # 9. 关闭连接
    conn.close()
print('操作结束!!!')

实例二

# 创建函数 查询
# 对数据单个的增加 修改 删除
# 1. 导包
import pymysql
# 2. 连接mysql服务端
conn = pymysql.connect(user='root',
                        password="",
                        host='127.0.0.1',
                        database='database',
                        port=3306,
                        charset="utf8", )
# 3. 创建游标对象
cur = conn.cursor()
try:
    # 4. 执行sql语句

    sql = 'selest * from orders'

    # 5. 使用游标对象执行sql
    cur.execute(sql)

    # 6. 获取结果
    result = cur.fetchall()
except Exception as e:
    print(e)
finally:
    # 7. 关闭游标对象
    cur.close()
    # 8. 关闭连接
    conn.close()
print('操作结束!!!')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值