博主辛苦了,我要打赏银两给博主,犒劳犒劳站长。
【摘要】本文给出一个完整的 python 单个页面处理 MySQL 数据库的完整实例。
二话不多说,直接给出完整代码:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import sys
import pymysql
import random
"""
数据库配置项
"""
db_host = "127.0.0.1" # 主机名
db_username = "root" # 数据库用户名
db_password = "root" # 数据库密码
db_name = "mafutian" # 数据库名称
db_port = 3306 # 数据库端口号,必须整型
db_charset = "utf8" # 连接字符集
# 对于支持事务的数据库, 在 Python 数据库编程中,当游标建立之时,就自动开始了一个隐形的数据库事务。
# commit() 方法游标的所有更新操作,rollback() 方法回滚当前游标的所有操作。
# MySQL 的存储引擎是 Innodb 才支持事务处理
try:
conn = pymysql.connect(
host = db_host,
user = db_username,
passwd = db_password,
db = db_name,
port = db_port,
charset = db_charset
)
except Exception as e:
# 发生异常,连接失败
print("数据库连接错误:",e)
# 退出整个程序。参数默认为0,表示正常退出,1表示异常退出
sys.exit(1)
else:
print("数据库连接成功")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = conn.cursor()
'''
创建表
'''
sql = """
CREATE TABLE IF NOT EXISTS `mafutian`(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
age INT,
summary VARCHAR(100)
);
"""
# MySQL 对建表、删表语句不支持事务
cursor.execute("DROP TABLE IF EXISTS `mafutian`")
cursor.execute(sql)
'''
插入数据
'''
# 注意此处的占位符全部是 %s 字符串类型,不区分字符串、整型、浮点型或者其它类型,且 %s 不加引号
sql = 'INSERT INTO `mafutian`(name,age,summary) VALUES({})'.format(','.join(['%s'] * 3))
values = [" mafutian ","18"," 中文 "]
count = 0
while (True):
if count > 1000:
break
else:
count += 1
age = random.randint(10, 30)
values[1] = str(age)
# 对每个字段进行处理,将两边的空格去掉
values = list(map(lambda x: x.strip(), values))
try:
cursor.execute(sql, values)
except Exception as e:
# 若已执行 sql,但不提交事务,或者事务回滚,主键会自增加1,但会删除该条记录
# 回滚当前事务
conn.rollback()
count -= 1 # 计数器减1
print('事务处理失败',e)
else:
# 每达到 100 条时, sql 执行一次事务
if count % 100 == 0:
# 提交当前事务
conn.commit()
print('提交事务',count)
# 当未达到 100 整时,将剩下的 sql 提交事务,避免遗漏
conn.commit()
print('提交事务')
'''
查询数据
'''
# 查询语句不需要提交事务
sql = "select id,name,age,summary from mafutian"
cursor.execute(sql)
# 返回数据条数或影响行数
tot = cursor.rowcount
print("已查询到的总行数",tot)
if tot > 0 :
# 返回的结果集是元组,元组的元素不能修改,元组使用小括号
# 取得结果集的下一行
row = cursor.fetchone()
# (1, 'mafutian', 29, '中文')
print(row)
# 获取结果集的下三行
rows = cursor.fetchmany(3)
# ((2, 'mafutian', 14, '中文'), (3, 'mafutian', 20, '中文'), (4, 'mafutian', 29, '中文'))
print(rows)
# 返回结果集剩下的所有行
# id 从 5 开始,((5, 'mafutian', 16, '中文'),...)
result = cursor.fetchall()
for row in result:
id = row[0]
name = row[1]
age = row[2]
summary = row[3]
print("id:",id," name:",name," age:",age," summary:",summary)
break
else:
print("查询结果为空")
'''
更新数据
'''
sql = "UPDATE mafutian SET summary = %s WHERE id = %s "
values = ['这是 python',10]
try:
cursor.execute(sql,values)
except Exception as e:
print('事务处理失败',e)
conn.rollback()
else:
conn.commit()
'''
删除数据
'''
# 这里依旧是 %s,不论字段类型是什么,都是采用 %s
sql = "DELETE FROM mafutian WHERE id > %s"
values = [10]
try:
cursor.execute(sql,values)
except Exception as e:
print('事务处理失败',e)
conn.rollback()
else:
conn.commit()
cursor.close() # 关闭游标对象
conn.close() # 关闭连接
另外,给出简洁版本:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import sys
import pymysql
db_host = "127.0.0.1"
db_username = "root"
db_password = "root"
db_name = "mafutian"
db_port = 3306
db_charset = "utf8"
try:
conn = pymysql.connect(host = db_host, user = db_username, passwd = db_password, db = db_name, port = db_port, charset = db_charset)
except Exception as e:
print("数据库连接错误:",e)
sys.exit(1)
else:
cursor = conn.cursor()
sql = "select id,name1,age,summary from mafutian"
try:
cursor.execute(sql)
except Exception as e:
print("查询错误",e)
sys.exit(1)
tot = cursor.rowcount
if tot > 0 :
result = cursor.fetchall()
for row in result:
print(row)
else:
print("查询结果为空")
cursor.close()
conn.close()
不积跬步无以至千里,不积小流无以成江海。
版权归 马富天个人博客 所有
本文标题:《Python 单个页面连接 MySQL 数据库,进行增删改实例》
本文链接地址:http://www.mafutian.com/395.html
转载请务必注明出处,小生将不胜感激,谢谢! 喜欢本文或觉得本文对您有帮助,请分享给您的朋友 ^_^
顶1
踩0
评论审核未开启 |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
||