下载安装模块
pip3 install mysql
使用操作
1.在python中使用sql语句
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='0123', db='test1', charset='utf8')#创建连接
cursor = conn.cursor()#创建游标
effect_row = cursor.execute('insert into user_info(name,part_nid)values("xiaohei", "1")')#查询数据
conn.commit()#提交操作
r = cursor.execute('select * from user_info where nid="1"')
conn.commit()
print(r, cursor.fetchall())#输出受影响的行数和执行的结果
cursor.scroll(0, mode='absolute')#设置内部指针的位置,绝对位置熊0开始
print(r, cursor.fetchone())
a = cursor.execute('select * from user_info where nid in (3,5)')
conn.commit()
print(a, cursor.fetchall())
cursor.close()#关闭游标
conn.close()#关闭连接
View Code
2.游标设置为字典类型
1 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
3.获取新创建数据自增id
1 new_id = cursor.lastrowid
4.关于fetch
fetchall()#获取全部数据
fetchone()#获取第一条
fetchmany(n)#获取多条
View Code