python--python操作MySQL
1 import pymysql 2 3 # 1. 创建连接 4 conn = pymysql.Connect( 5 host='数据库连接地址', 6 user='账号', 7 password='密码', 8 db='库名', 9 charset='utf8', 10 ) 11 print(conn) 12 13 # 2.创建游标 14 # 传递参数cursor=pymysql.cursors.DictCursor 返回的数据就是字典结构 15 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 16 17 # 3.执行SQL语句 18 res = cursor.execute('select * from table order by id desc limit 10') 19 print(res) # 返回影响的数据条数,或查询的条数 20 21 # 4.获取结果---默认情况下返回的是元组 22 one = cursor.fetchone() # 获取一条 23 print(one) 24 three = cursor.fetchmany(3) # 获取三条 25 print(three) 26 rest = cursor.fetchall() # 获取所有 27 print(rest) 28 29 # 5.关闭游标 30 cursor.close() 31 32 # 6.关闭连接 33 conn.close()