- 向MongoDB傳數據
from pymongo import MongoClient #導入庫對應的庫localhost = "172.16.0.203" #數據庫IP地址
baseName = "GreenNagoya"
client = MongoClient(localhost, 27017, username="admin", password="zdiai@123") #數據庫端口、賬號及密碼database = client["Repo_history"] #需要鏈接到具體哪個數據庫
collection = database[baseName] #需要鏈接數據庫中的哪張表#data里面是需要傳入的key值,key的話需要根據產品提供的key來
data = {"engineSpeed":100,"rotationRate":120,"speedOnWater":11,"seaFuel":121,"hostPower":123,"groundSpeed":122,"totalPower":144,"shipSlipRate":134,"rudderAngle":12,"shipBow":32,"somskey1":333,"test_somekey02":34,"test_somekey":12,"fuelEfficiency":56,}
collection.insert_one(data)
2.向redis傳入數據
import redis# 連接到 Redis 的 2 號庫
try:r = redis.Redis(host='172.16.2.225',port=6379,password='zdiai@123',db=2,decode_responses=True)# 測試連接r.ping()print("成功連接到 Redis 的 2 號庫")# 要發送的數據data = {"GJDV000000507": 0.0,"GJAQ000000184": 135.78398387830148,"GJAQ000000185": 210.68863292915802,"GJAQ000000182": 0.0,"GJAQ000000183": -19.183531240737473,"GJAQ000000180": 0.0,"GJAQ000000181": 0.0,"GJAQ000000179": 0.0,"WaterDepth": 11.63,"GJAQ000000153": 5.35572092959191,"timestamp": 1744801910,"GJAQ000000162": 0.0,"GJAQ000000163": 0.0,}# 往 Redis 中設置數據for key, value in data.items():r.set(key, value)print("數據已成功發送到 Redis 的 2 號庫")except redis.exceptions.ConnectionError:print("無法連接到 Redis,請檢查主機、端口和密碼。")
except redis.exceptions.AuthenticationError:print("Redis 認證失敗,請檢查密碼。")
except Exception as e:print(f"發生未知錯誤: {e}")