Import Pymysql,redis
def opertiomsql (host,user,passwd,db,sql,port=3306,charset= ' UTF8 '):
conn = Pymysql.connect (host=host,user=user,passwd=passwd,port=port,db=db,charset=charset) #建立链接
cur = conn.cursor (cursor=pymysql.cursors.dictcursor) #建立游标
Cur.execute (SQL) #执行sql
If Sql.startswith (' select '):
res = Cur.fetchall ()
Else
Conn.commit ()
res = 88
Cur.close ()
Conn.close ()
return res
def Opredis (host,passwd,k,v=false,port=6379,db=0):
R = Redis. Redis (HOST=HOST,PASSWORD=PASSWD,PORT=PORT,DB=DB)
#连接数据库
If V: #判断value是否传值, if passed, the description is the Set method
R.set (K,V)
res = 88
Else
res = R.get (k). Decode ()
#因为从redis里面获取到数据都是字节类型的, to turn it into a string
#所以要用decode方法
return res
if __name__ = = ' __main__ ':
sql = ' select * from user; '
sql2= "INSERT into user (ID, username, password) VALUES (3, ' test2 ', 123)"
# s = opertiomsql (host= ' 10.0.1.82 ', user= ' Byz ', passwd= ' 123456 ', db= ' Byz ', sql=sql)
# print (s)
s = Opredis (' 211.149.218.16 ', ' 123456 ', ' Nhy:word ',)
Print (s)
Python Operations Database