Python 小练习二 数据库MySQL、Redis

 

 1 import pymysql,redis
 2 def op_mysql(host,user,password,db,sql,port=3306,charset='utf8'):
 3     conn = pymysql.connect(host=host,user=user,
 4                            password=password,
 5                            port=port,
 6                            charset=charset,db=db)
 7     cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
 8     cur.execute(sql)
 9     sql_start = sql[:6].upper() #取sql前6个字符串,判断它是什么类型的sql语句
10     if sql_start=='SELECT' :
11         res = cur.fetchall()
12     else:
13         conn.commit()
14         res = 'ok'
15     cur.close()
16     conn.close()
17     return res
18 
19 def op_redis(host,password,k,v=None,port=6379,db=0):
20     r = redis.Redis(host=host,password=password,port=port,db=db)
21     if v:
22         r.set(k,v)
23         res = 'ok'
24     else:
25         res = r.get(k)
26         if res: #这里是判断有没有get到数据
27             res = res.decode()
28         else:
29             res = None
30     return res
31 
32 print(__name__)
33 print('前面哈')
34 if __name__=='__main__':
35     #别人导入这个python文件的时候,下面的代码不会被执行
36     #自己测试的时候用
37     # print(__name__)  # __main__
38     print('后面哈')
39     sql = 'select * from bt_stu limit 5;'
40     sql2 = 'update bt_stu set class="test123" where id=503;'
41     res = op_mysql(
42         host='211.149.xxx.16',
43         user='jxz',password='123456',#port这里一定要写int类型
44         port=3306,db='jxz',charset='utf8',sql=sql2)
45     print(res)

 

posted on 2018-01-25 21:32  louis_w  阅读(275)  评论(0编辑  收藏  举报

导航