1、MySQL操做補充html
cur = coon.cursor(cursor=pymysql.cursors.DictCursor)
創建遊標的時候指定了遊標類型,返回的就是一個字典了。
fetchall() #獲取到這個sql執行的所有結果,它把數據庫表裏面的每一行數據放到一個list裏面
[ ['1','2','3'] ] [{},{},{}]
fetchone() #獲取到這個sql執行的一條結果,它返回就只是一條數據
若是sql語句執行的結果是多條數據的時候,那就用fetchall()
若是你能肯定sql執行的結果就只有一條,那麼就用fetchone()
enumerate([list,list2]) #循環的時候,直接獲取到下標,和值
for index,value in enumerate([list,list2]):#list2裏面是什麼?
print(index,vlaue)
fileds = ['id','name','sex','addr','gold','score'] for index,filed in enumerate(fileds): print(index,filed)
運行結果:node
0 id 1 name 2 sex 3 addr 4 gold 5 score
一個返回數據庫表頭字段的函數:python
import pymysql def my_db(sql,port=3306,charset='utf8'): import pymysql host, user, passwd, db = '118.24.3.40','jxz','123456','jxz' coon = pymysql.connect(user=user,host=host,port=port,passwd=passwd,db=db,charset=charset) cur = coon.cursor(cursor=pymysql.cursors.DictCursor) #創建遊標,指定cursor類型返回的是字典 cur.execute(sql)#執行sql if sql.strip()[:6].upper()=='SELECT': # res = cur.fetchall() fileds = [] # for filed in cur.description:#cur.description可直接獲取到建表時的字段描述信息,如('id', 253, None, 40, 40, 0, True) # fileds.append(filed[0]) fileds = [ filed[0] for filed in cur.description ] #和上面3行代碼的意思是同樣 print(fileds) # cur.fetchmany() #能傳入一個數,返回多少條數據 res= 'xx' else: coon.commit() res = 'ok' cur.close() coon.close() return res res = my_db('select * from users_info limit 10;')#limit用於指定返回的數據條數 print(res)
運行結果:mysql
['id', 'username', 'passwd'] xx
enumerate函數:同時獲取到list的下表和值linux
fileds = ['id','name','sex','addr','gold','score'] for index,filed in enumerate(fileds): print(index,filed)
運行結果:web
0 id 1 name 2 sex 3 addr 4 gold 5 score
練習:通用數據庫導出到EXCEL函數redis
import pymysql,xlwt def export_excel(table_name): host, user, passwd, db = '118.24.3.40', 'jxz', '123456', 'jxz' coon = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset='utf8') cur = coon.cursor() # 創建遊標,指定cursor類型返回的是字典 sql = 'select * from %s ;'%table_name cur.execute(sql) # 執行sql fileds = [filed[0] for filed in cur.description] #全部的字段 all_data = cur.fetchall()#全部的數據 book = xlwt.Workbook() sheet= book.add_sheet('sheet1') for col,filed in enumerate(fileds): #寫表頭的 sheet.write(0,col,filed) row = 1 #行數 for data in all_data: #data爲每一行數據 for col, filed in enumerate(data): # 控制列寫入 sheet.write(row, col, filed) row+=1#每次寫完一行,行就加1 book.save('%s.xls'%table_name) export_excel('app_student')
2、操做Excelsql
修改Excel:數據庫
import xlrd from xlutils import copy book = xlrd.open_workbook('app_student.xls') #先用xlrd模塊,打開一個excel new_book = copy.copy(book) #經過xlutils這個模塊裏面copy方法,複製一份excel sheet = new_book.get_sheet(0) #獲取sheet頁 lis = ['編號','名字','性別','年齡','地址','班級','手機號','金幣'] for col,filed in enumerate(lis): sheet.write(0,col,filed) new_book.save('app_student.xls')
讀取Excel:apache
import xlrd book = xlrd.open_workbook('app_student.xls') sheet = book.sheet_by_index(0)#根據索引獲取sheet頁 # sheet2 = book.sheet_by_name('sheet1')#根據名稱獲取sheet頁 print(sheet.cell(0,0).value) #指定sheet頁裏面第一行和第一列獲取數據 print(sheet.cell(1,0).value) #指定sheet頁裏面第2行和第1列獲取數據 print(sheet.row_values(0)) #獲取到第1行的內容 print(sheet.row_values(1)) #獲取到第2行的內容 print(sheet.nrows) #獲取到excel裏面總共有多少行 for i in range(sheet.nrows): #知道行數後,循環獲取到每行數據 print(sheet.row_values(i)) print(sheet.ncols) #總共多少列 print(sheet.col_values(0)) #取第幾列的數據
3、操做Redis
redis是一個nosql類型的數據庫,數據都存在內存中,有很快的讀寫速度,python操做redis使用redis模塊,pip安裝便可
redis數據所有都是存在內存裏面。
redis自己性能是很是好的,每秒支持30w次的讀寫。
import redis r = redis.Redis(host='118.24.3.40',password='HK139bc&*',db=1,port=6379)#鏈接redis #增刪改查 r.set('niuhanyang','帥!') #數據庫裏面新增一個值 # hwt = r.get('niuhanyang')#查,根據key獲取對應的值 # print(hwt.decode()) #修改也是set r.delete('niuhanyang') r.setex('python_123','哈哈哈',20) #設置key的失效時間,最後這個參數是秒,時間事後,即刪掉這個KEY hwt = r.get('mei')#獲取到的是二進制 爲bytes類型 print(hwt.decode())#將bytes類型轉換爲字符串類型,encode將字符串轉換爲bytes print(hwt) print(r.keys('*xxx*'))#獲取到全部含xxx的key print(r.keys())#獲取到全部的KEY print(r.get('sdfsdf')) r.set('今天是2018年6月9日:mpp','呵呵呵')#Key中有的冒號的,冒號前面爲文件夾的名稱,同一個文件夾的內容均可以這樣存入 r.set('今天是2018年6月9日:dict','今天是星期六') for k in r.keys(): #刪除全部的key r.delete(k) # 上面操做都是針對 string類型 # 哈希類型 hash 相似嵌套字典 r.hset('stu_info','劉偉','1m8 100w存款') r.hset('stu_info','張流量','浪,爲了避免交做業,故意讓狗咬他') r.hset('stu_info','董春光','爲了避免交做業,找了一條狗咬張流量,而後陪張流量去醫院') # print(r.type('stu_info'))#查看key的類型 # print(r.hget('stu_info','張流量').decode()) #指定大key和小key獲取對應的數據 # print(r.hgetall('stu_info')) #獲取裏面全部的k和-v stu_info = r.hgetall('stu_info')#獲取到stu_info下的全部k-v print(stu_info) stu_dic={} for k,v in stu_info.items():#stu_info.items()獲取到全部的k-v # print(k.decode(),v.decode()) stu_dic[k.decode()]=v.decode() print(stu_dic) r.hdel('stu_info','gyx') #刪除指定key r.delete('stu_info') #刪除整個key r.expire('aaa',100) #設置失效時間 print(r.type('stu_info')) #查看key是什麼類型的 print(r.type('zll')) s='呵呵' s.encode() #把字符串轉成二進制 hwt = b'sdfsdfsdf' hwt.decode() #把bytes類型轉成字符串 #pymysql、json、redis #一、連數據庫,查到數據庫裏面全部的數據,遊標類型要用pymysql.curosrs.DictCour #二、查到全部數據 [ {"id":1,"passwd":"49487dd4f94008a6110275e48ad09448","username":"niuhayang","is_admin":1}] #三、循環這個list,取到usernamer,把username當作key #四、再把這個小字典轉成json,存進去就ok import pymysql,json,redis r = redis.Redis(host='118.24.3.40',password='HK139bc&*',db=1,port=6379) conn = pymysql.connect(host='118.24.3.40',user='jxz',passwd='123456',db='jxz',charset='utf8') cur = conn.cursor(cursor=pymysql.cursors.DictCursor) cur.execute('select * from my_user;') all_data = cur.fetchall() for data in all_data: k = data.get('username') r.hset('stu_info_nhy',k,json.dumps(data)) cur.close() conn.close() #下面這個是我本身寫的 import pymysql,redis,json r=redis.Redis(host='118.24.3.40',password='HK139bc&*',db=1,port=6379) coon=pymysql.connect(host='118.24.3.40',user='jxz',passwd='123456',db='jxz',charset='utf8') cur=coon.cursor(cursor=pymysql.cursors.DictCursor) cur.execute('select * from my_user;') res=cur.fetchall() for data in res: username=data.get('username') data_json=json.dumps(data)#此處代碼可參考上面老師寫的進行精簡 r.hset('my_user',username,data_json) cur.close() coon.close()
4、接口開發
import flask,json #輕量級的web開發框架 #做爲服務端,來開發接口供別人調用,需先啓動一個服務 server=flask.Flask(__name__)#__name__表明當前這個python文件, # 這句代碼的意思就是把我們當前的python文件當作一個服務,下面要在這個服務上開發一個接口 #*******get請求能夠在瀏覽器直接訪問,post請求需經過第三方工具調用***** # ****操做數據庫**** def my_db(sql): import pymysql coon = pymysql.connect( host='118.24.3.40', user='jxz', passwd='123456', port=3306, db='jxz', charset='utf8') cur = coon.cursor() #創建遊標 cur.execute(sql)#執行sql if sql.strip()[:6].upper()=='SELECT': res = cur.fetchall() else: coon.commit() res = 'ok' cur.close() coon.close() return res # ****操做數據庫****
# *******第一個接口******* #ip:8080/index?uge @server.route('/index',methods=['get','post'])#這句代碼的意思是下面這個函數將做爲服務裏的一個接口, # 再也不是一個普通的函數;調用這個接口時,就調用index這個路徑,methonds爲支持調用的方法, # 能夠post或get,也能夠都寫,也能夠不寫,不寫默認爲get方法 def index(): res={'msg':'這是我開發的第一個接口','msd_code':0}#這是一個字典,下面調用時要轉換成json串 return json.dumps(res,ensure_ascii=False) # server.run(port=7777,debug=True)#啓動服務,能夠指定端口號,不寫時默認爲5000,debug=True,改了代碼以後,不用重啓它會自動幫你重啓 #這時就能夠直接在瀏覽器訪問這個接口:http://127.0.0.1:7777/index
# *******第一個接口*******
# *******註冊用戶接口******* @server.route('/reg',methods=['post'])#post請求不能直接在瀏覽器訪問 def reg(): username=flask.request.values.get('username')#接收用戶輸入 pwd=flask.request.values.get('passwd')#接收用戶輸入 if username and pwd: sql='select * from my_user where username="%s";'%username #這裏由於%s未加雙引號致使sql執行失敗,sql必定要寫正確,切記切記 if my_db(sql): res={'msg':'用戶已存在','msg_code':2001} else: insert_sql='insert into my_user (username,passwd,is_admin) values ("%s","%s",0);'%(username,pwd) my_db(insert_sql) res={'msg':'註冊成功!','msg_code':0} else: res={'msg':'必填字段未填,請查看接口文檔!','msg_code':1001}#1001 必填字段未填 return json.dumps(res,ensure_ascii=False)
# *******註冊用戶接口*******
server.run(port=7777,debug=True,host='0.0.0.0')#啓動服務,能夠指定端口號,不寫時默認爲5000,debug=True,改了代碼以後,不用重啓它會自動幫你重啓 #在postman中輸入參數調用該註冊接口,可正確返回結果
瀏覽器調用結果:
postman調用註冊接口執行狀況:
註冊成功:
用戶已存在:
5、項目開發文件邏輯
單獨的一個python文件不叫程序,叫腳本;複雜的程序一般都會分目錄存儲,方便修改和查閱,提升代碼的可讀性。例如:bin目錄下放置啓動文件,啓動程序時直接執行該目錄下的文件便可;config目錄下放置配置文件,主要是一些端口或IP地址等;lib目錄下放置接口文件及本身開發的一些工具程序;log下存放日誌;data下放置初始化數據等;還應包含readme文件。
下面PS一片Linux下的目錄層級說明: