python3 pymysql

介绍

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

安装

pip install pymysql

  

本地数据库操作

mysql> create database mydb1;
#Query OK, 1 row affected

mysql> use mydb1;
#Database changed

mysql> create table users(
    -> id int not null auto_increment primary key,
    -> name char(8) not null,
    -> age tinyint unsigned not null,
    -> sex char(4) not null,
    -> tel char(13) null default "-"
    -> );
#Query OK, 0 rows affected

mysql> commit;
#Query OK, 0 rows affected

  

基本操作

import pymysql
# 连接mysql
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='1234',db='mydb1')

# 获取游标
cur = conn.cursor()

try:
    # 使用execute执行sql语句
    reCount = cur.execute('select * from users;')
    # reCount = cur.execute('insert into users(name,age,sex) values(%s,%s,%s)', ('momo', '13','male'))
    # reCount = cur.execute('insert into users(name,age,sex) values(%(age)s, %(name)s, %(sex)s)',{'sex':'female,'name':'pig','age':10})

    
    # 使用fetchone 获取一条数据
    data = cur.fetchone()
    
    # 使用fetchall 获取所有数据
    #data = cur.fetchall()
    
    # 提交命令
    conn.commit()
except:
    # 发生错误回滚
    conn.rollback()

# 关闭游标
cur.close()

# 关闭数据库连接
conn.close()
  
print(reCount)
print(data)

  

创建数据库表

 1 #!/usr/bin/python3
 2 
 3 import pymysql
 4 
 5 # 打开数据库连接
 6 db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 7 
 8 # 使用 cursor() 方法创建一个游标对象 cursor
 9 cursor = db.cursor()
10 
11 # 使用 execute() 方法执行 SQL,如果表存在则删除
12 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
13 
14 # 使用预处理语句创建表
15 sql = """CREATE TABLE EMPLOYEE (
16          FIRST_NAME  CHAR(20) NOT NULL,
17          LAST_NAME  CHAR(20),
18          AGE INT,  
19          SEX CHAR(1),
20          INCOME FLOAT )"""
21 
22 cursor.execute(sql)
23 
24 # 关闭数据库连接
25 db.close()
创建数据库表

数据库插入数据

 1 #!/usr/bin/python3
 2 
 3 import pymysql
 4 
 5 # 打开数据库连接
 6 db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 7 
 8 # 使用cursor()方法获取操作游标 
 9 cursor = db.cursor()
10 
11 # SQL 插入语句
12 sql = "INSERT INTO EMPLOYEE(FIRST_NAME, 
13        LAST_NAME, AGE, SEX, INCOME) 
14        VALUES ('%s', '%s', '%d', '%c', '%d' )" % 
15        ('Mac', 'Mohan', 20, 'M', 2000)
16 try:
17    # 执行sql语句
18    cursor.execute(sql)
19    # 执行sql语句
20    db.commit()
21 except:
22    # 发生错误时回滚
23    db.rollback()
24 
25 # 关闭数据库连接
26 db.close()
insert

查询

 1 #!/usr/bin/python3
 2 
 3 import pymysql
 4 
 5 # 打开数据库连接
 6 db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 7 
 8 # 使用cursor()方法获取操作游标 
 9 cursor = db.cursor()
10 
11 # SQL 查询语句
12 sql = "SELECT * FROM EMPLOYEE 
13        WHERE INCOME > '%d'" % (1000)
14 try:
15    # 执行SQL语句
16    cursor.execute(sql)
17    # 获取所有记录列表
18    results = cursor.fetchall()
19    for row in results:
20       fname = row[0]
21       lname = row[1]
22       age = row[2]
23       sex = row[3]
24       income = row[4]
25        # 打印结果
26       print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % 
27              (fname, lname, age, sex, income ))
28 except:
29    print ("Error: unable to fecth data")
30 
31 # 关闭数据库连接
32 db.close()
select

更新

 1 #!/usr/bin/python3
 2 
 3 import pymysql
 4 
 5 # 打开数据库连接
 6 db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 7 
 8 # 使用cursor()方法获取操作游标 
 9 cursor = db.cursor()
10 
11 # SQL 更新语句
12 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
13                           WHERE SEX = '%c'" % ('M')
14 try:
15    # 执行SQL语句
16    cursor.execute(sql)
17    # 提交到数据库执行
18    db.commit()
19 except:
20    # 发生错误时回滚
21    db.rollback()
22 
23 # 关闭数据库连接
24 db.close()
update

删除

 1 #!/usr/bin/python3
 2 
 3 import pymysql
 4 
 5 # 打开数据库连接
 6 db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 7 
 8 # 使用cursor()方法获取操作游标 
 9 cursor = db.cursor()
10 
11 # SQL 删除语句
12 sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
13 try:
14    # 执行SQL语句
15    cursor.execute(sql)
16    # 提交修改
17    db.commit()
18 except:
19    # 发生错误时回滚
20    db.rollback()
21 
22 # 关闭连接
23 db.close()
delete

事务

 1 # SQL删除记录语句
 2 sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
 3 try:
 4    # 执行SQL语句
 5    cursor.execute(sql)
 6    # 向数据库提交
 7    db.commit()
 8 except:
 9    # 发生错误时回滚
10    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的子类。
原文地址:https://www.cnblogs.com/xp1005/p/6650824.html