一、PyMySQL

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

二、安装

pip install PyMySQL

三、测试连接数据库

import pymysql
# 打开数据库连接
db = pymysql.connect(host="127.0.0.1", user="root", password="4100107223", database="user", port=3306)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 关闭数据库连接
db.close()

四、创建数据库

import pymysql
# 打开数据库连接
db = pymysql.connect(host = "127.0.0.1", port = 3306, user = "root", password = "4100107223", database = "user")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("drop table if exists employee")
# 使用预处理语句创建表
sql = """create table employee (
         first_name  char(20) not null,
         last_name  char(20),
         age int,  
         sex char(1),
         income float )"""
cursor.execute(sql)
# 关闭数据库连接
db.close()

五、插入数据

import pymysql
# 打开数据库连接
db = pymysql.connect(host = "127.0.0.1", port = 3306, user = "root", password = "4100107223", database = "user")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 插入语句
sql = """insert into employee(first_name,
         last_name, age, sex, income)
         values ('mac', 'mohan', 20, 'm', 2000)"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()
# 关闭数据库连接
db.close()

六、查询数据

import pymysql
# 打开数据库连接
db = pymysql.connect(host = "127.0.0.1", port = 3306, user = "root", password = "4100107223", database = "user")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句
sql = "select * from employee where income > '%d'" % (1000)
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        # 打印结果
        print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (fname, lname, age, sex, income ))
except:
    print ("Error: unable to fetch data")
# 关闭数据库连接
db.close()

七、删除数据

import pymysql
# 打开数据库连接
db = pymysql.connect(host = "127.0.0.1", port = 3306, user = "root", password = "4100107223", database = "user")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句
sql = "delete from employee where age = '%d' " % (21)
try:
    # 执行SQL语句
    len = cursor.execute(sql)
    print('删除了', len, '条记录')
    # 提交到数据库执行
    db.commit()
except:
    # 发生错误时回滚
    db.rollback()
    print ("出现异常了")
# 关闭数据库连接
db.close()

八、修改数据

import pymysql
# 打开数据库连接
db = pymysql.connect(host = "127.0.0.1", port = 3306, user = "root", password = "4100107223", database = "user")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句
sql = "update employee set age = age + 1 where sex = '%c'" % ('m')
try:
    # 执行SQL语句
    len = cursor.execute(sql)
    print('修改了', len, '条记录')
    # 提交到数据库执行
    db.commit()
except:
    # 发生错误时回滚
    db.rollback()
    print ("出现异常了")
# 关闭数据库连接
db.close()

九、事务

# SQL删除记录语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 向数据库提交
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()

十、错误处理

Warning					当有严重警告时触发,例如插入数据是被截断等等。必须是 StandardError 的子类。
Error					警告以外所有其他错误类。必须是 StandardError 的子类。
InterfaceError			当有数据库接口模块本身的错误(而不是数据库的错误)发生时触发。 必须是Error的子类。
DatabaseError			和数据库有关的错误发生时触发。 必须是Error的子类。
DataError				当有数据处理时的错误发生时触发,例如:除零错误,数据超范围等等。 必须是DatabaseError的子类。
OperationalError		指非用户控制的,而是操作数据库时发生的错误。例如:连接意外断开、 数据库名未找到、事务处理失败、内存分配错误等等
						操作数据库是发生的错误。 必须是DatabaseError的子类。
IntegrityError			完整性相关的错误,例如外键检查失败等。必须是DatabaseError子类。
InternalError			数据库的内部错误,例如游标(cursor)失效了、事务同步失败等等。 必须是DatabaseError子类。
ProgrammingError		程序错误,例如数据表(table)没找到或已存在、SQL语句语法错误、 参数数量错误等等。必须是DatabaseError的子类。
NotSupportedError		不支持错误,指使用了数据库不支持的函数或API等。例如在连接对象上 使用.rollback()函数,
						然而数据库并不支持事务或者事务已关闭。 必须是DatabaseError的子类。

十一、使用数据库的预编译 Python预编译语句防止SQL注入

args = (id, type)
cur.execute('select id, type ,name from xl_bugs where id = %s and type = %s', args )

或者这样
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

文章信息

张雪随笔
master
Homepage
Issues
Download

This Software is under the terms of The Unlicense.