一、安装:cmd——pip3 install pymysql

二、操作mysql
1、导入mysql
import pymysql
2、也数据库建立连接
conn = pymysql.connect(host='localhost',port=3306,user='root',passwd='',db='chouti')
3、创建游标
方式一:cursor = conn.cursor()
方式二:cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
区别:方式一游标取值结果是元组形式,方式二游标取值结果是列表形式,推荐使用方式二,
4、执行sql语句
方式一:cursor.execute()
方式二:cursor.executemany()
区别:方式一操作数据库一条数据,方式二同时操作数据库多条数据,
注意一:无论方式一还是方式二,都有返回值,返回操作涉及的数据总数,
5、获取sql查找结果
方式一:cursor.fetchone()
方式二:cursor.fetchmany(n)
方式三:cursor.fetchall()
区别:方式一获取第一条数据,方式二获取接下来的n条数据,方式三获取之后的所有数据,
注意:游标可以进行relative相对位移和absolute绝对位移:cursor.scroll(),详见代码。
6、确认提交(增、删、改,需要commit提交至数据库刷新,查不需要)
conn.commit()
7、关闭游标
cursor.close()
8、关闭连接
conn.close()
import pymysql conn = pymysql.connect(host='localhost',port=3306,user='root',passwd='',db='chouti') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # effect_row = cursor.execute("insert into all_user(name,pwd) values(%s,%s)",('luna',888)) # print('涉及的总行数:',effect_row) # print('最后的自增ID值:',cursor.lastrowid) # # effect_row = cursor.executemany("insert into all_user(name,pwd) values(%s,%s)",[('lucy',111),('luna',222),('even',333)]) # print('涉及的总行数:',effect_row) # print('最后的自增ID值:',cursor.lastrowid) effect_row = cursor.execute("select * from all_user where user_type >%s;",(0,)) print('共有%s条记录符合条件。'%effect_row) ret_one = cursor.fetchone() print('一条:',ret_one) ret_another = cursor.fetchone() print('又一条:',ret_another) ret_many = cursor.fetchmany(2) print('再两条:',ret_many) ret_all = cursor.fetchall() print('剩余全部:',ret_all) cursor.scroll(-4,'relative') ret_many = cursor.fetchmany(2) print('退4,取2',ret_many) cursor.scroll(1,'relative') ret_one = cursor.fetchone() print('退4,取2;进1,取1',ret_one) cursor.scroll(2,'absolute') ret_many = cursor.fetchmany(2) print('起点进2:',ret_many) conn.commit() cursor.close() conn.close()
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
- cursor.scroll(1,mode='relative') # 相对当前位置移动
- cursor.scroll(2,mode='absolute') # 相对绝对位置移动
浙公网安备 33010602011771号