PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库
数据库连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import pymysql
db = pymysql.connect("localhost","root","010616dhy","testDB")
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print("Database version : %s " % data)
db.close()
|
插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| ... sql_insert = '''insert into employee(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) values('Dong', 'Hanyu',19,'M',200 )''' try: cursor.execute(sql_insert) db.commit() except: print("error!") db.rollback() ...
|
使用变量向SQL语句中传递参数:
1 2 3 4 5
| user_id = "test123" password = "password"
con.execute('insert into Login values( %s, %s)' % \ (user_id, password))
|
查询
- fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
- fetchall(): 接收全部的返回结果行.
- rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import pymysql
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
show = "SELECT * FROM EMPLOYEE \ WHERE INCOME > %s" % (100) try: cursor.execute(show) results = cursor.fetchall() for i in results: print("fname=%s,lname=%s,age=%s,sex=%s,income=%s " % \ (i[0],i[1],i[2],i[3],i[4])) except: print ("Error: unable to fetch data")
db.close()
|
更新
1 2 3 4 5 6 7 8 9 10 11
| db = pymysql.connect("localhost","root","010616dhy","testDB") cursor = db.cursor() sql = "update employee set age=age+1 where sex='%c'" % ('m') try: cursor.execute(sql) db.commit() except: print("error") db.rollback()
db.close()
|
删除
1 2 3 4 5 6 7 8 9 10
| db = pymysql.connect("localhost","root","010616dhy","testDB") cursor = db.cursor() sql = "delete from employee where age > %s" % (19) try: cursor.execute(sql) db.commit() except: print("del error") db.rollback() db.close()
|
执行事务
事务应该具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性。
- 原子性(atomicity)。一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
- 一致性(consistency)。事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
- 隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
- 持久性(durability)。持续性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。
1 2
| db.commit() 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的子类。 |