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()

转载于:https://www.cnblogs.com/yago/p/11443720.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值