mongo&SqlServer

操作mongoDB 和SQLServerDB的方法

import traceback, pyodbc
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
from Utilities.logger import logger
from Utilities.test_env import ENVINFO
import urllib3

class MongoDbHelper():

@classmethod
def get_mongodb_collection(cls, pod, collection_name, hk_or_uk=None):
connection = ENVINFO().mongdb(pod, hk_or_uk)
try:
client = MongoClient(connection)
db = client.get_database()
collection = db.get_collection(collection_name)
return collection
except ConnectionFailure as c:
raise c

def get_mongodb_connect_to_admin(self,pod, db_name, collection_name,hk_or_uk=None):
connection = ENVINFO().mongdb(pod,None)#wwm,None
try:
client = MongoClient(connection)#MongoDBConnection=mongodb://sit_user:Mon04Jan@hkl20107453.hc.cloud.hk.hsbc:5255/admin
db = client.get_database(db_name)#wwm_sit1_hk
collection = db.get_collection(collection_name)#wwmcases
return collection
except ConnectionFailure as c:
raise c

@classmethod
def connect_to_mongodb_to_admin(cls,clientname, tablename): #clientname为连接到DB,tablename为connection
myclient = MongoClient(ENVINFO().MongoDBAdmin())
mydb = myclient[clientname]
mycol = mydb[tablename]
return mycol
def update_meetingDate_to_yesterday(self, id):
yesterday = (date.today() - timedelta(days=1)).strftime('%Y-%m-%d')
agenda_item_coll = MongoDbHelper().get_mongodb_collection('CMA', 'cma_agenda_item')
agenda_item_coll.update_one({'_id': ObjectId(id)}, {'$set': {"meetingDate": yesterday}})

def delete_one_meeting(self, id):
agenda_item_coll = MongoDbHelper().get_mongodb_collection('CMA', 'cma_agenda_item')
agenda_item_coll.delete_one({'_id': ObjectId(id)})

def delete_many_meeting(self):
meetingDate = (date.today() + timedelta(days=7)).strftime("%Y-%m-%d")
agenda_item_coll = MongoDbHelper().get_mongodb_collection('CMA', 'cma_agenda_item')
agenda_item_coll.delete_many({'meetingDate': meetingDate})


def delete_all_meeting(self):
agenda_item_coll = MongoDbHelper().get_mongodb_collection('CMA', 'cma_agenda_item')
logger.info(role_staffid_dic['rmUserName_name'])
agenda_item_coll.delete_many({'createdBy': role_staffid_dic['rmUserName_name']})
def get_count_of_ma_template_from_mongodb(self, customerid):
collection = MongoDbHelper().get_mongodb_collection('CMA', 'cma_agenda_template')
count = collection.count({"customerId": customerid})
logger.info(count)
return count
db.getCollection('trigger_exception_report').find({'requestBody.customerId':"HK001013"})

class SQLServerDbHelper():

def get_connect(self):
server = ENVINFO().sqlserver()
logger.info(server)
connect = pyodbc.connect(server)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
return connect

def close_credit_sql(self, cursor, connect):
try:
if cursor != None: cursor.close()
except:
print(traceback.format_exc())
finally:
if connect != None: connect.close()

def execute_sql(self, sql):
try:
connect = self.get_connect()
cursor = connect.cursor()
cursor.execute(sql)
connect.commit()
except:
print(traceback.format_exc())
finally:
self.close_credit_sql(cursor, connect)

def excute_query_sql(self, sql):
try:
connect = self.get_connect()
cursor = connect.cursor()
cursor.execute(sql)
result = cursor.fetchall()
return result
except :
print(traceback.format_exc())
finally:
self.close_credit_sql(cursor, connect)

def execute_credit_sql(self, sql):
try:
is_successful = True
connect = self.get_connect()
cursor = connect.cursor()
cursor.execute(sql)
connect.commit()
except:
connect.rollback()
is_successful = False
finally:
self.close_credit_sql(cursor, connect)
return is_successful

def combine_into_dict(self, key_list, value_list):
dict = {}
for key in key_list:
dict.update({key: value_list[key_list.index(key)]})
return dict

 

插入多行数据

 

 mongoDB 查询大全

https://blog.csdn.net/qq_41853447/article/details/108539155

posted @ 2022-03-01 12:26  苍耳冬阳  阅读(96)  评论(0编辑  收藏  举报