pymysql
python操作数据库的基本步骤:
- 导入相应的python模块;
- 使用connect函数连接数据库,并返回一个connection对象;
- 通过connection对象的cursor方法,返回一个cursor对象;
- 通过cursor对象的execute方法执行SQL语句;
- 如果执行的是查询语句,通过cursor对象的fetchall语句获取返回结果;
- 调用cursor对象的close方法关闭cursor;
- 调用connection对象的close方法关闭数据库连接。
1 import pymysql 2 3 conn = pymysql.Connect(host='127.0.0.1',user='admin',passwd='admin',db='test_py') 4 cur = conn.cursor() 5 6 reCount = cur.execute('select * from student') 7 print(cur.fetchall()) # ((1, 'gareth', 22, datetime.date(2011, 9, 1)),) 8 9 cur.close() 10 conn.close()
connection类成员
- begin: 开始事务
- commit: 提交事务
- rollback: 回滚事务
- cursor: 返回一个cursor对象
- autocommit: 设置是否事务自动提交
- set_character_set: 设置字符集编码
- get_server_info: 获取数据库版本信息
注: 一般不直接调用begin,commit和roolback函数,而是通过上下文管理器实现事务的提交与回滚操作。
cursor类成员对象:cursor对象表示数据库游标,用于执行SQL语句并获取SQL语句的执行结果。
- execute: 执行SQL语句
- close:关闭游标
- fetchall:获取SQL语句的所有记录
- fetchmany:获取SQL语句的多条记录
- fetchone:获取SQL语句的一条记录
- owncount:常量,表示SQL语句的结果集中返回了多少条记录
- arraysize:变量,保存了当前获取纪录的下标
- lastrowid:获取最新自增ID
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
- cursor.scroll(1,mode='relative') # 相对当前位置移动
- cursor.scroll(2,mode='absolute') # 相对绝对位置移动
默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
1 conn = pymysql.Connect(host='127.0.0.1',user='admin',passwd='admin',db='test_py') 2 cur = conn.cursor(cursor=pymysql.cursors.DictCursor) 3 4 reCount = cur.execute('select * from student') 5 print(cur.fetchall()) 6 """ 7 [{'stu_id': 1, 'name': 'gareth', 'age': 22, 'register_data': datetime.date(2011, 9, 1)}, 8 {'stu_id': 3, 'name': 'Bob', 'age': 19, 'register_data': datetime.date(2012, 2, 3)}, 9 {'stu_id': 4, 'name': 'Bob', 'age': 19, 'register_data': datetime.date(2012, 2, 3)}, 10 {'stu_id': 5, 'name': 'Mary', 'age': 18, 'register_data': datetime.date(2013, 1, 2)}] 11 """ 12 13 cur.close() 14 conn.close()
使用上下文管理管理数据库:
1 import pymysql 2 import os 3 4 5 def get_conn(**kwargs): 6 if os.getenv('DB','MYSQL') == 'MYSQL': 7 return pymysql.connect(host=kwargs.get('host','localhost'), 8 user=kwargs.get('user'), 9 passwd=kwargs.get('passwd'), 10 port=kwargs.get('port',3306), 11 db=kwargs.get('db')) 12 13 def execute_sql(conn, sql): 14 with conn as cur: 15 cur.execute(sql) 16 17 def insert_data(conn,sname,sage,sregister): 18 INSERT_FORMAT = """insert into student (name,age,register_data) values('{0}','{1}','{2}')""" 19 sql = INSERT_FORMAT.format(sname,sage,sregister) 20 execute_sql(conn,sql) 21 22 def main(): 23 conn = get_conn(host='127.0.0.1', 24 user='admin', 25 passwd='admin', 26 port=3306, 27 db='test_py') 28 29 try: 30 insert_data(conn,'Bob',19,'2012-02-03') 31 insert_data(conn,'Mary',18,'2013-01-02') 32 33 with conn as cur: 34 cur.execute('select * from student') 35 rows = cur.fetchall() 36 for row in rows: 37 print(row) 38 finally: 39 if conn: 40 conn.close() 41 42 if __name__ == '__main__': 43 main()