-
python 连接MySQL
-
import pymysql class DB(): """ 与 统计 数据库交互 """ def __init__(self, user=feed_username, # 服务器用户名 passwd=feed_password, # 服务器密码 host=feed_ip, # 服务器IP port=<feed_port>, # 数据库端口号 db=<database_name>, # 数据库名称 charset='utf8'): retry_times = 3 # 重试3次 for i in range(retry_times): try: self.db_connect = pymysql.connect(host=host, port=port, db=db, user=user, passwd=passwd, charset=charset) self.db_cursor = self.db_connect.cursor(cursor=pymysql.cursors.DictCursor) break except Exception as e: print('重复连接数据库|{0}|{1}'.format(i, e)) continue def __enter__(self): return self.db_cursor def __exit__(self, exc_type, exc_val, exc_tb): self.db_connect.commit() self.db_cursor.close() self.db_connect.close()
# 执行原生SQL语句 with DB() as db: db.execute(sql) # sql 为原生语句 data_dict = db.fetchone() # 如果sql是查询语句, 此处获得字典类型数据 data_list = db.fetchall() # 如果sql是查询语句, 此处获得列表类型数据 # 此处可以使用循环语句执行一系列的 sql语句
-
-
python 连接 MongoDB
-
from pymongo import MongoClient class MongoAPI(object): def __init__(self, db_ip, # 服务器IP db_port, # 端口号:27017 db_name, # 数据库名称 table_name # 表名称 ): self.db_ip =db_ip self.db_port = db_port self.db_name = db_name self.table_name = table_name self.conn = MongoClient(host=self.db_ip, port=self.db_port) self.db = self.conn[self.db_name] self.table = self.db[self.table_name] def get_one(self, query): return self.table.find_one(query, projection={"_id": False}) def get_all(self, query): return self.table.find(query) def add(self, kv_dict): return self.table.insert(kv_dict) def delete(self, query): return self.table.delete_many(query) def check_exist(self, query): ret = self.table.find_one(query) return ret != None # 如果没有会新建 def update(self, query, kv_dict): self.table.update_one(query, {'$set': kv_dict}, upsert=True)
# 建立连接,并操作mongodb数据库 db_post = MongoAPI('localhost', 27017, 'db_test', 'table_test') db_post.update({"post_link": 3}, {"title": 2, "post_link": 3, "author": 4, "author_link": 3})
-