1 安装
pip install pymysql
2 地址
https://pypi.org/project/pymysql/
3 数据查询
import pymysql
# 查询操作
def func_database_search():
global db
# 打开数据库连接
try:
db = pymysql.connect(host='127.0.0.1', user='admin', passwd='123456', port=3306,
db='test')
print('连接成功!')
except:
print('something wrong!')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT url FROM news"
try:
# 执行SQL语句
cursor.execute(sql)
# 获取返回数量
row_count = cursor.rowcount
print(type(row_count))
print(row_count)
'''
<class 'int'>
16
'''
# 获取所有记录列表 fetchall返回二维元组(元组中含有元组)
results = cursor.fetchall()
print(type(results))
print(results)
'''
<class 'tuple'>
(('baidu.com',), ('cctv.com',))
'''
for row in results:
scan_url = row[0]
# 打印结果
print('数据查询成功!')
except:
print("Error: unable to fetch data")
# 关闭数据库连接
db.close()
if __name__ == '__main__':
func_database_search()
参考链接:
https://zhuanlan.zhihu.com/p/397765212
http://www.xoxxoo.com/index/index/article/id/288