| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 
 | DB 模块(只支持 3 以下版本)开始
 创建connection
 获取cursor
 。。。
 关闭cursor
 关闭connrction
 结束
 
 在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。
 PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL。
 如果还未安装,我们可以使用以下命令安装最新版的 PyMySQL:
 
 $ pip install PyMySQL
 现在用pymysql模块
 connection 数据库连接对象
 cursor	数据库交互对象
 exceptions 数据库异常类
 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1', charset='utf8')
 
 
 游标对象:用于执行查询和获取结果
 cursor = conn.cursor()
 
 
 
 
 cursor.execute("SELECT VERSION()")
 
 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)
 
 
 data = cursor.fetchone()
 
 
 sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
 LAST_NAME, AGE, SEX, INCOME)
 VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
 try:
 
 cursor.execute(sql)
 
 db.commit()
 except:
 
 db.rollback()
 
 conn.commit()
 
 cursor.close()
 
 conn.close()
 
 游标的使用
 获取缓冲区内的数据行数(执行cursor.execute()方法后会把数据缓冲到缓冲区)
 cursor.rowcount
 
 effect_row = cursor.execute("select * from tb7")
 
 row_1 = cursor.fetchone()
 
 row_2 = cursor.fetchmany(3)
 
 row_3 = cursor.fetchall()
 
 在执行cursor.execute()语句时
 如果出现异常
 则conn.rollback() 回滚事务
 如果没出现
 则conn.commit() 提交事务
 
 事务 : 访问和更新数据库的一个程序的执行单元
 开发中使用事务
 首先要自动关闭事务(commit)
 conn.autocommit(false)
 正常结束事务
 比如执行(更改) insert 操作,就需要用下面命令提交执行,否则无法生效
 conn.commit()
 异常结束事务(会使上述所有的执行都没有生效)
 conn.rollback()
 
 |