简介:Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口。使用它连接各数据库后,就可以用相同的方式操作各数据库。
Python DB-API使用流程

  • 引入 API 模块。
  • 获取与数据库的连接。
  • 执行SQL语句和存储过程。
  • 关闭数据库连接。

操作mysql

  • 安装MYSQL驱动
    //使用阿里云镜像
    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple mysql-connector
  • api操作
# 导入MySQL驱动:
import mysql.connector
import random

# 打开数据库连接
db = mysql.connector.connect(user='root', password='admin', database='hy')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 创建表
cursor.execute('create table IF NOT EXISTS py_zx (id int(20) NOT NULL AUTO_INCREMENT,name varchar(20) ,PRIMARY KEY (`id`))')
#随机创建10条
for x in range(10):
    cursor.execute('insert into py_zx (name) values (%s)',[random.randint(0,100)])
# 提交事务
db.commit()

# 查询结果
cursor.execute('select * from py_zx')
# 取结果集
values=cursor.fetchall()
print(values)
# 关闭Cursor和Connection
cursor.close()
db.close()

小结

  • 执行INSERT等操作后要调用commit()提交事务;
  • MySQL的SQL占位符是%s。
Logo

更多推荐