Python DB API 规范
我们在使用 Python 对 DBMS 进行操作的时候,需要经过下面的几个步骤:
- 引入 API 模块;
- 与数据库建立连接;
- 执行 SQL 语句;
- 关闭数据库连接。
如何使用 mysql-connector
pip install mysql-connector
import mysql.connector
# 打开数据库连接
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="123456", # 写上你的数据库密码
database='nbaplayers',
# auth_plugin='mysql_native_password'
)
# 获取操作游标
cursor = db.cursor()
# 执行 SQL 语句
cursor.execute("SELECT VERSION()")
# 获取一条数据
data = cursor.fetchone()
print("MySQL 版本: %s " % data)
# 关闭游标 & 数据库连接
cursor.close()
db.close()
- 1. 通过指定 host、user、passwd 和 port 等参数来创建数据库连接,这些参数分别对应着数据库 IP 地址、用户名、密码和端口号;
- 2. 使用 db.close() 关闭数据库连接;
- 3. 使用 db.cursor() 创建游标,操作数据库中的数据;
- 4. 使用 db.begin() 开启事务;
- 5. 使用 db.commit() 和 db.rollback(),对事务进行提交以及回滚。
-
1. 使用
cursor.execute(query_sql)
,执行数据库查询; -
2. 使用
cursor.fetchone()
,读取数据集中的一条数据; -
3. 使用
cursor.fetchall()
,取出数据集中的所有行,返回一个元组 tuples 类型; -
4. 使用
cursor.fetchmany(n)
,取出数据集中的多条数据,同样返回一个元组 tuples; -
5. 使用
cursor.rowcount
,返回查询结果集中的行数。如果没有查询到数据或者还没有查询,则结果为 -1,否则会返回查询得到的数据行数; -
6. 使用
cursor.close()
,关闭游标。
对数据表进行增删改查
增加数据。
# 插入新球员
sql = "INSERT INTO player (team_id, player_name, height) VALUES (%s, %s, %s)"
val = (1003, " 约翰 - 科林斯 ", 2.08)
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, " 记录插入成功。")
# 查询身高大于等于 2.08 的球员
sql = 'SELECT player_id, player_name, height FROM player WHERE height>=2.08'
cursor.execute(sql)
data = cursor.fetchall()
for each_player in data:
print(each_player)
修改数据呢
# 修改球员约翰 - 科林斯
sql = 'UPDATE player SET height = %s WHERE player_name = %s'
val = (2.09, " 约翰 - 科林斯 ")
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, " 记录被修改。")
删除数据
sql = 'DELETE FROM player WHERE player_name = %s'
val = (" 约翰 - 科林斯 ",)
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, " 记录删除成功。")
cursor.close()
db.close()
- 1. 打开数据库连接以后,如果不再使用,则需要关闭数据库连接,以免造成资源浪费。
- 2. 在对数据进行增加、删除和修改的时候,可能会出现异常,这时就需要用
try...except
捕获异常信息。比如针对插入球员约翰·科林斯这个操作,你可以写成下面这样:
import traceback
try:
sql = "INSERT INTO player (team_id, player_name, height) VALUES (%s, %s, %s)"
val = (1003, " 约翰 - 科林斯 ", 2.08)
cursor.execute(sql, val)
db.commit()
print(cursor.rowcount, " 记录插入成功。")
except Exception as e:
# 打印异常信息
traceback.print_exc()
# 回滚
db.rollback()
finally:
# 关闭数据库连接
db.close()
- 3. 如果你在使用 mysql-connector 连接的时候,系统报的错误为
authentication plugin caching_sha2
,这时你需要下载最新的版本更新来解决,点击这里进行更新。