#coding:utf-8
import pymysql#导入mysql包
import pymongo#导入MongoDB包
#打开MySQL数据库链接
#获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
#port 必须是数字不能为字符串
db = pymysql.connect(host="主机名",user="用户名",password="密码",db="数据库名称",port=3306,charset='utf8')
#使用cursor()
cur = db.cursor()
#连接MongoDB数据库
mongo_client = pymongo.MongoClient('MongoDB主机名', 27017)
mongo_auth = mongo_client['数据库名称']
mongo_auth.authenticate('用户名', '密码')
#1. 查询操作
#编写查询语句bus_equipment对应我的表名
sql = "select * from 表名"
count1 = 0
count2 = 0
try:
cur.execute(sql) #执行sql语句
results = cur.fetchall() #获取查询的所有记录
#遍历结果
for row in results:
gatherID = row[3]
count1 += 1
collection = mongo_auth[gatherID]
for item in collection.find():
count2 += 1
print("总数据条数:"+count2)
print("gather_id总数:"+count1)
# 关闭连接
mongo_client.close()
except Exception as e:
raise e
finally:
db.close()
![]()