python使用mysql

python使用mysql

  1. 导包 import pymysql
  2. 创建和mysql服务端的连接对象 py.connnect(参数列表)
  3. 获取游标对象 cusor = 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

# 1.连接mysql数据库的服务
conn = pymysql.Connect(
    # mysql服务器端的IP,默认127.0.0.1/localhost/真实IP
    host = '127.0.0.1',
    user = 'root',
    password = 'root',
    database = 'py',
    port = 3306,
)
# 2.创建游标对象
cur = conn.cursor()
# 3.编写SQL
sql = 'select * from students;'
# 4.使用游标对象去调用SQL
cur.execute(sql)
# 5.获取查询的结果
result = cur.fetchall()
print(result)
# 6.关闭游标对象
cur.close()
# 7.关闭连接
conn.close()

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

import pymysql

# 1.连接mysql数据库的服务
conn = pymysql.Connect(
    # mysql服务器端的IP,默认127.0.0.1/localhost/真实IP
    host = '127.0.0.1',
    user = 'root',
    password = 'root',
    database = 'py',
    port = 3306,
)
# 2.创建游标对象
cur = conn.cursor()
try:
    # 3.编写SQL
    # 增加数据
    sql = 'insert into students values(%s,%s,%s,%s);'
    add_data = [0,'wangwu','30','女']
    # 修改数据
    sql1 = 'update students set name = %s where name = "zhangsan"'
    update_data = ['zhaoliu']
    # 删除数据
    sql2 = 'delete from students where name = %s'
    del_data = ['lisi']
    # 4.使用游标对象去调用SQL
    cur.execute(sql,add_data)
    cur.execute(sql1,update_data)
    cur.execute(sql2,del_data)
    # 5.提交操作
    conn.commit()
except Exception as e:
    print(e)
    # 数据回滚
    conn.rollback()
finally:
    # 6.关闭游标对象
    cur.close()
    # 7.关闭连接
    conn.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值