目录一、关于python操作数据库的概述二、一般操作流程三、安装Mysql的操作库四、基本操作一、关于Python操作数据库的概述 Python所有的数据库接口程序都在一定程度上遵守
Python所有的数据库接口程序都在一定程度上遵守 Python DB-api 规范。
DB-API定义了一系列必须的对象和数据库存取方式,以便为各种底层数据库系统和多种多样的数据库接口程序提供一致的访问接口。由于DB-API 为不同的数据库提供了一致的访问接口, 在不同的数据库之间移植代码成为一件轻松的事情。
在Python中如果要连接数据库,不管是mysql、SQL Server、postgresql亦或是sqlite,使用时都是采用游标的方式。
$ pip3 install PyMySQL
创建连接
import pymysql
# 创建连接方式1
db = pymysql.connect(host='localhost',
user='root', passWord='root', db='test', port=3306)
# 创建连接方式2
db = pymysql.connect(dsn='localhost:test', user='root', password='root')
close()
关闭此connect对象, 关闭后无法再进行操作,除非再次创建连接。
cursor()
创建游标对象。一个游标允许用户执行数据库命令和得到查询结果。一个 Python DB-API 游标对象总是扮演游标的角色, 无论数据库是否真正支持游标。也就说,数据库接口程序必须实现游标对象。创建游标对象之后, 你就可以执行查询或其它命令(或者多个查询和多个命令), 也可以从结果集中取出一条或多条记录。
commit()
提交当前事务,执行游标对象的所有更新操作。
rollback()
取消当前事务,回滚当前游标的所有操作。
游标操作
cursor = db.cursor()
查询操作
import pymysql
db = pymysql.connect(host='localhost', user='root', password='root', db='test')
cursor = db.cursor()
sql = '''select * from t_account'''
try:
cursor.execute(sql)
# 方式1读取结果集
rows = cursor.fetchall()
for row in rows:
print(row)
# 方式2读取结果集
for i in range(cursor.rowcount):
result = cursor.fetchone()
print(result)
except Exception as e:
raise e
finally:
cursor.close()
db.close()
添加操作
import pymysql
db = pymysql.connect(host='localhost', user='root', password='root', db='test')
cursor = db.cursor()
sql = '''insert into t_account values(default,'zhangsan','z',100,'张三')'''
try:
print(cursor.execute(sql))
db.commit()
except:
db.rollback()
finally:
cursor.close()
db.close()
修改操作
import pymysql
db = pymysql.connect(host='localhost', user='root', password='root', db='test')
cursor = db.cursor()
sql = '''update t_account set realname = '李四' where id = '5' '''
try:
print(cursor.execute(sql))
db.commit()
except:
db.rollback()
finally:
cursor.close()
db.close()
删除操作
import pymysql
db = pymysql.connect(host='localhost', user='root', password='root', db='test')
cursor = db.cursor()
sql = '''delete from t_account where id = '5' '''
try:
print(cursor.execute(sql))
db.commit()
except:
db.rollback()
finally:
cursor.close()
db.close()
调用存储过程
cursor.callproc("存储过程名称")
for result in cursor.fetchall():
print(result)
到此这篇关于教你怎么用Python操作MySql数据库的文章就介绍到这了,更多相关Python操作MySql内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 教你怎么用Python操作MySql数据库
本文链接: https://www.lsjlt.com/news/127261.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-06-06
2024-06-06
2024-06-05
2024-06-04
2024-06-04
2024-06-03
2024-06-03
2024-06-03
2024-06-04
2024-06-03
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0