python数据库操作(oracle、redis、mongo、mysql)

一、oracle

1、用python连接Oracle是总是乱码,最后发现时oracle客户端的字符编码设置不对。

  编写的python脚本中需要加入如下几句:

  import os
  os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

  参考来源:https://www.cnblogs.com/chenjianhong/p/4144399.html

2、特殊符号

  如果字符中含有&等特殊符号,需要特殊处理;

  'kkkkk' || '&' || 'kkkkkk'

3、连接

import cx_Oracle
def element(cols,row)
  elem=dict()
  for i in range(len(cols)):
    elem[cols[i]]=row[i]
try:
  db= cx_Oracle.connect(username/passwd@host:port/sevicename)
  cr=db.cursor()
  cr.execute(sql)  #执行sql
  rows=cursor.fetchall()  #以元组方式返回所有记录,参考:https://www.cnblogs.com/z-x-y/p/9055509.html
  cols=map(lambda x:x[0],cr.description)  #返回该表的每个字段名
  result=map(lambda row:elem(cols,row),rows)  #返回类似   [{字段名1:字段值1,字段名2:字段值2},{},{}] 的结果
except Exception,e:
  print 'connect error',e
finally:
  #db.commit()
  db.close()
db= cx_Oracle.connect(username/passwd@host:port/sevicename)
cur=db.cursor()
cur.execute(sql.encode("utf-8"))
result_list = cur.fetchall()
cols = cur.description
db.close()

col = [i[0] for i in cols]
res = [{key: value for key, value in zip(col, i)} for i in result_list]
#返回上面类似的结果,包括mysql也可以这样处理
二、redis 
import redis

con=redis.StricrRedis(host='',port='',db='',password='')

print con.get('键')
print con.set('键','值')
print con.keys('键*')
class redis_dao:
    '''
    这个是给项目内部逻辑判断使用的
    '''

    def __init__(self, default=None, con=REDIS_CONFIG):
        self.redis_obj = redis.Redis(**con)
        self.default = default

    def query(self, key):
        data = self.redis_obj.get(key) if self.default == None else self.redis_obj.get(f"{self.default}.{key}")
        return json.loads(data) if data else None

    def insert(self, key, value):
        self.redis_obj.set(key, value) if self.default == None else self.redis_obj.set(f"{self.default}.{key}", value)
        return

    def delete(self, key):
        result = self.redis_obj.delete(key) if self.default == None else self.redis_obj.delete(f"{self.default}.{key}")
        return result if result else None


redis_ex = redis_dao(default=REDIS_GATEWAY_PH, con=REDIS_CONFIG)


def operate_redis(args, con=REDIS_CONFIG):
    '''
    REDIS_CONFIG={"host": '示例', "port": '6379', "db": '示例', "password": ''}
    这个是给本地通过接口操作redis时使用的,请求示例
    {
    "type":"query",
    "space": "示例",
    "key": "示例",
    "value" : "test"
    }
    '''
    redis_obj = redis.Redis(**con)
    key = f"{args.get('space')}.{args.get('key')}"

    if args.get("type") == "query":
        data = redis_obj.get(key)
        return json.loads(data) if data else None
    if args.get("type") == "delete":
        result = redis_obj.delete(key)
        return result if result else None
    if args.get("type") in ["update", "insert"]:
        redis_obj.set(key, args.get('value'))
        return
    return "type字段错误"

三、mongo

1、查询数组中是否含有某值(数组中是基础类型数据、数组中是对象)https://blog.csdn.net/besmarterbestronger/article/details/100536766

2、模糊查询 https://www.cnblogs.com/xibuhaohao/p/12049788.html

3、and和or条件 https://www.jb51.net/article/197366.html

 

# 这里用了逻辑and、in条件、elemMatch匹配条件、regex模糊查询(data是find函数的入参)
           data= {'$and': [{"id_account": {'$in': [99166774, 49144443]}},
                           {"installment_detail": {'$elemMatch': {'status': 'Paid'}}},
                           {"invitation_code": {'$regex':'1'}}]
            }

4、下面是dao逻辑

class mongo_dao:
    '''
    这个是给项目内部逻辑判断使用的
    '''

    def __init__(self, database, url):
        myclient = pymongo.MongoClient(url, connect=False)
        db = myclient[database.get("space")]
        self.col = db[database.get("db")]

    def query(self, args):
        result = list(self.col.find(args).sort("created_at", -1))
        return result if len(result) > 0 else False

    def query_latest(self, args):
        mongo_result = self.query(args)
        return mongo_result[0] if mongo_result else {}

    def insert(self, args):
        result = self.col.insert_many(args)
        return result.inserted_ids

    def delete(self, args):
        result = self.col.delete_many(args)
        return result.deleted_count

    def update(self, args, update):
        result = self.col.update_many(args, update)
        return result.modified_count


# 实例
mongo_ex = mongo_dao(database={"space": "示例", "db": "示例"}, url=MONGO_URL)


def operate_mongo(args, url=MONGO_URL):
    '''
    这个是给本地通过接口操作mongo时使用的,请求示例
    {
    "type":"query",
    "space": "示例",
    "db": "示例",
    "data": {"id_account": 26280},
    "updata": {"id_account": 26281}
    }
    '''
    myclient = pymongo.MongoClient(url, connect=False)
    mydb = myclient[args.get("space")]
    mycol = mydb[args.get("db")]
    if args.get("type") == "query":
        result = list(mycol.find(args.get("data")).sort("created_at", -1))
        data = []
        for r in result:
            r.pop('_id')
            data.append(r)
        return result if len(data) > 0 else False
    if args.get("type") == "insert":
        result = mycol.insert_many(args.get("data"))
        return result.inserted_ids
    if args.get("type") == "delete":
        result = mycol.delete_many(args.get("data"))
        return result.deleted_count
    if args.get("type") == "update":
        result = mycol.update_many(args.get("data"), args.get("updata"))
        return result.modified_count
    return "type字段错误"

 四、mysql

1、关于sqlalchemy,参考:https://www.cnblogs.com/chenxi67/p/10376617.html

2、关于pymysql

因为query和handle中都有db.close,所以创建的mysql_dao对象只能执行一次方法。可以根据需求修改封装的方法

account = {"host": 测试, "user": 测试, "password": 测试, "port": 3306}

class mysql_dao:
    def __init__(self, db):
        self.db = pymysql.connect(**account, database=db)
        self.cur = self.db.cursor()

    def query(self, sql):
        self.cur.execute(sql)
        result_list = self.cur.fetchall()  # 获取查询结果
        cols = [i[0] for i in self.cur.description]  # 获取字段名
        self.db.close()
        return [{key: value for key, value in zip(cols, i)} for i in result_list] if result_list else None

    def handle(self, *sql):
        try:
            for i in sql:
                self.cur.execute(i)
            self.db.commit()
        except Exception as e:
            print(f"操作异常:{e}")
            self.db.rollback()
        finally:
            self.db.close()

五、单表操作的sql拼接

def link_condition(**data):
    '''value目前只考虑了str、tuple、数字类型'''
    s = ''
    if data:
        for key, value in data.items():
            if isinstance(value, str):
                s += f" and {key} = '{value}' " if value else ''
            elif isinstance(value, tuple):
                if len(value) > 1:
                    s += f" and {key} in {value} " if value else ''
                elif len(value) == 1 and isinstance(value[0], str):
                    s += f" and {key} = '{value[0]}' " if value else ''
                else:
                    s += f" and {key} = {value[0]} " if value else ''
            else:
                s += f" and {key} = {value} " if value else ''
    return " where 1=1 " + s

 

posted @ 2019-09-12 11:37  whitewall  阅读(270)  评论(0)    收藏  举报