python读写mysql数据库

python对mysql数据库的连接可由 pymysql 模块实现。

基本步骤:连接数据库、创建游标对象、读写操作、关闭游标、关闭连接。

示例:

建立一个数据库,命名python_mysqlconnect_demo,创建两张表,命名table1table2,表结构均为

1-1.插入一条数据

向table1中插入记录:(1, 'name1')

import pymysql

# 1.连接数据库
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='xxx',
    db='python_mysqlconnect_demo',
    charset='utf8'
)

# 2.创建游标对象
cur = conn.cursor()

# 3.操作
try:
    insert_one_sql = "insert into table1 values(1, 'name1');"
    cur.execute(insert_one_sql)
except Exception as e:
    print("插入数据失败:", e)
else:
    conn.commit()
    if(cur.rowcount > 0):
        print("插入数据成功。")

# 4.关闭游标
cur.close()
# 5.关闭连接
conn.close()

1-2.插入多条数据

向table2中插入记录:(1, 'name1')至(10, 'name10')

# 3.操作
try:
    insertList = []
    for i in range(10):
        insertList.append((i+1,"name%s"%(i+1)))

    insert_multi_sql = "insert into table2 values(%s, %s);"
    cur.executemany(insert_multi_sql, insertList)

except Exception as e:
    print("插入多条数据失败!", e)
else:
    conn.commit()
    if (cur.rowcount > 0):
        print("插入多条数据成功。")

2-1.删除一条数据

删除table1中id为1的记录

# 3.操作
try:
    delete_one_sql = "delete from table1 where id=1;"
    cur.execute(delete_one_sql)
except Exception as e:
    print("删除数据失败:", e)
else:
    conn.commit()
    if (cur.rowcount > 0):
        print("删除数据成功;")

2-2.删除表中所有数据

删除table2中的所有记录

# 3.操作
try:
    delete_all_sql = "delete from table2;"
    cur.execute(delete_all_sql)
except Exception as e:
    print("删除数据失败:", e)
else:
    conn.commit()
    if (cur.rowcount > 0):
        print("删除数据成功;")

3.修改一条数据

将table1中id为1记录的name值改为“name111”

# 3.操作
try:
    update_sql = "update table1 set id=1,name='name111;'"
    cur.execute(update_sql)
except Exception as e:
    print("更新数据失败:", e)
else:
    conn.commit()
    if (cur.rowcount > 0):
        print("更新数据成功;")

4-1.查询一条数据

查询table2中id为6的记录

# 3.操作
select_one_sql = "select * from table2 where id=6;"
cur.execute(select_one_sql)
print(cur.fetchone())

4-2.查询表中全部数据

查询table2中的所有记录

# 3.操作
select_all_sql = "select * from table2;"
cur.execute(select_all_sql)
result_tuple = cur.fetchall()     # 获取所有的查询结果,类型是元组
print(result_tuple)

参考

  1. python连接数据库_Carol_小菜鸟的博客-CSDN博客_python连接数据库
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

禺垣

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

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

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

打赏作者

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

抵扣说明:

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

余额充值