python 连接mysql

 

from APItest.common.config import *
import pymysql

# 通过pymysql 连接数据库
mysql = pymysql.connect(host=handle.cp.get('db', 'host'),
port=handle.cp.getint('db', 'port'),
user=handle.cp.get('db', 'user'),
password=handle.cp.get('db', 'pwd'),
charset='utf8',
autocommit=True)

# 指定返回的数据是字典格式,有两种办法
# 1, 在连接是指定
mysql1 = pymysql.connect(host=handle.cp.get('db', 'host'),
port=handle.cp.getint('db', 'port'),
user=handle.cp.get('db', 'user'),
password=handle.cp.get('db', 'pwd'),
charset='utf8',
autocommit=True,
cursorclass='DictCursor')
# 2,在建立游标时指定
cursor = mysql.cursor(pymysql.cursors.DictCursor)

# 新建一个查询页面
cursor2 = mysql.cursor() # 建立游标,保存查询结果,游标每次读取到结果之后,指标就会往下走
# 编写sql
sql = "select MAX(MobilePhone) from future.member where MobilePhone like '135%'"
sql1 = "select * from future.member where MobilePhone like '135%'"
# 执行sql
cursor.execute(sql1)
# 查看,获取结果
max_phone = cursor.fetchone() # 获取结果集里面最近的一条,返回元组
max_phone2 = cursor.fetchone()
print(max_phone)
print(max_phone2)

# 获取全部的数据,返回元组
all_data = cursor.fetchall() # 制定了返回数据格式的话,fetchne 就是字典,fetchall 就是列表里面嵌套字典了
print(all_data)

# 关闭查询页面
cursor.close()
# 关闭连接
mysql.close()
posted @ 2019-09-01 21:22  yago白菜  阅读(179)  评论(0编辑  收藏  举报