总共分为八个步骤:
1.导包
2.连接数据库
3.创建游标对象
4.定义sql语句
5.执行
6.获取数据的方式
7.关闭游标连接
8.关闭数据库
# 1.导包
import pymysql
# 2.连接数据库
# 例如connect=pymysql.connect(host="192.168.6.41",user="lrtsaudio",password="2&Ty3DW75i!(vgo.l3Odp1fgWgEG",port=3306,db="audiobook")
connect=pymysql.connect(host='127.0.0.1',user='root',password='root',port=3306,db='student',charset='utf8')
# 3.创建游标对象
# 创建一个游标对象:有两种创建方法
# cursor=connect.cursor()
# 或:cursor=pymysql.cursors.Cursor(connect)
cursor=pymysql.cursors.Cursor(connect)
# 4.定义sql语句
# 注意如果做 insert uodate delete 要进行提交 不提交sql不会生效
# db.commit()
# 例如sentence="SELECT book_id,book_name FROM t_book WHERE market_rule=1"
sentence1="insert into info values(null ,'小锋',23,'男',15679900072) "
sentence2="delete from info where name='小谢'"
sentence3="select * from info "
connect.commit()
# 5.执行
# 使用游标的execute()方法执行sql语句
# cursor.execute(sentence)
# cursor.execute(sentence1)
# cursor.execute(sentence2)
cursor.execute(sentence3)
# 6.获取数据的方式
# fetchone() 获取一条数据
# fetchall() 获取所有查询到的数据
# fetchmany() 获取其中几行的结果
# rowcount 属性 返回数据影响的行数
# cursor.scroll(sele,value,mode="")重置游标位置
# value: 偏移量 大于0向后移动; 小于0向前移动
# mode: relative:表示从当前所在的行开始移动; absolute:表示从第一行开始移动 (默认relative)
# row_1=cursor.fetchone()
# row_2=cursor.fetchmany(3)
row_3=cursor.fetchall()
# print(row_1)
# print(row_2)
for i in row_3:
print(i,end='\n')
# 7.关闭游标连接
# cursor.close()
cursor.close()
# 8.关闭数据库连接
# connect.close()
connect.close()
'''
Cursor对象注意事项
一条链接在任何时候只会有一个Cursor对象处于查询状态,这是因为底层的TDS协议没有客户端侧的Cursor,协议要求客户端在进行下一次查询前先完成上一次的。
因此如果你想同时在一个连接上进行两个查询的话可能会出现各种惊喜,也许在使用多线程等方式的时候需要特别注意这点
'''
输出结果如下:
(1, '小谢', 21, '男', '15679900066')
(2, '小光', 24, '男', '15679900067')
(3, '小豪', 25, '男', '15679900068')
(4, '小蛋', 19, '男', '15679900069')
(5, '小银', 18, '男', '15679900070')
(6, '小文', 18, '男', '15679900071')
(13, '小锋', 23, '男', '15679900072')