使用python操作Mysql

2019-11-07  本文已影响0人  LittleJessy
Python DB API规范
image.png

这个规范给我们提供来数据库对象连接,对象交互和异常处理的方式,为各种DBMS提供来统一的访问接口。

使用Python对DBMS进行操作

需要经过下面的步骤:

  1. 引入API模块;
  2. 与数据库建立连接;
  3. 执行SQL语句;
  4. 关闭数据库连接;
# -*- coding: UTF-8 -*-
import mysql.connector
# 打开数据库连接
db = mysql.connector.connect(
       host="localhost",
       user="root",
       passwd="XXX", # 写上你的数据库密码
       database='wucai', 
       auth_plugin='mysql_native_password'
)
# 获取操作游标 
cursor = db.cursor()
# 执行SQL语句
cursor.execute("SELECT VERSION()")
# 获取一条数据
data = cursor.fetchone()
print("MySQL版本: %s " % data)
# 关闭游标&数据库连接
cursor.close()
db.close()

对数据库的当前连接操作:

通过cursor = db.cursor()创建游标后,可以对数据库中的数据进行操作:

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()
ORM框架

ORM的英文是Object Relation Mapping,中文叫做对象关系映射。采用ORM,可以从数据库的设计层面转化成面向对象的思维。


image.png

三种主流的ORM框架:

上一篇 下一篇

猜你喜欢

热点阅读