常用数据库交互代码
mysql
import pymysql
class database(object):
def __init__(self):
'''-----connection连接点------cursor光标-----'''
self.conn = pymysql.connect(host='localhost',port=3306,database='数据库名',user='root',password='1',charset='utf8')
self.cs = self.conn.cursor()
def database_Mysql(self,inf):
'''添加数据(字典)'''
sql = 'insert into qidian({}) values({})'.format(','.join(inf.keys()), ','.join(['%s'] * len(inf)))
try:
count = self.cs.execute(sql, [value for key, value in inf.items()])#不用list(inf.values())防sql注入
print('ok')
self.conn.commit()
except Exception as err:
print(err)
self.conn.rollback()
if __name__ == '__main__':
database()
mongo
import pymongo
class database(object):
def __init__(self):
'''-----client客户端-----[数据库][集合]-----'''
self.client = pymongo.MongoClient('localhost',27017)
self.db = self.client['数据库名字']
self.set = self.db['集合名字']
def database_Mongo(self,info):
'''添加数据(字典)'''
self.col.insert(info)
redis 配置
主从(信息唯一)
集群(信息共享)
redis(mysql交互)
redis
import redis
网友评论