Python操作MySQL数据库的增删改查完整脚本示例

阿澈
阿澈
发布时间:2026-10-14 | 4人浏览过
原创

本文提供基于Python的pymysql库操作MySQL数据库的完整脚本示例。内容涵盖数据库连接配置、数据查询(含fetchmany用法)、数据插入、更新及删除操作的具体代码实现,并展示了如何将查询结果写入Excel文件。适用于需要快速掌握Python与MySQL交互开发的开发者参考。

Python连接MySQL数据库及基础操作代码


# -*- coding: utf-8 -*-
import pymysql
import xlrd
# import codecs
#连接数据库
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='test_hvr', charset='utf8')
cursor = conn.cursor()

# 查询数据库
effect_row = cursor.execute("select * from kkpb_account where user_name='18800000000'")
row_1 = cursor.fetchmany(10)
print(row_1)
for row in row_1:
  with open('ha.xls','a')as f:
    f.write(str(row[0]))
#   print(row[0])

# 使用预处理语句创建表
# sql = """CREATE TABLE EMPLOYEE (
#     FIRST_NAME CHAR(20) NOT NULL,
#     LAST_NAME CHAR(20),
#     AGE INT,
#     SEX CHAR(1),
#     INCOME FLOAT )"""
# cursor.execute(sql)

# 数据库插入数据
# s_id='25'
# name='aaa'
# price='154.21'
# sql="insert into stu (id) VALUES ('%s')"%(s_id,)
# add_row=cursor.execute(sql)

# 删除数据
# name='asds'
# sql="delete from user where name = '%s'" % name
# dele_row=cursor.execute(sql)

# 更新数据
# userid='10'
# sql="update user set price=124.21 where userid='%s'"%userid
# upd_row=cursor.execute(sql)

conn.commit()
cursor.close()
conn.close()

总结与参考资源

以上就是Python操作MySQL数据库进行增删改查的脚本详细内容,更多关于Python操作MySQL数据库的资料请关注本站其它相关文章!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表