操作mysql,獲取欄位屬性值,並輸出表資料
阿新 • • 發佈:2019-02-05
import pymysql import decimal import datetime import json import LogPackage import logging import os logs=LogPackage.Logger(filename='log.txt',path=1,driver_path=os.getcwd()) logs.Log() logger=logging.getLogger(__name__) __description__='Finding the data in the same database' class DecimalEncoder(json.JSONEncoder): def default(self,obj): if isinstance(obj,decimal.Decimal):#decimal型別轉換,使其可以轉換為json格式資料 return float(obj) elif isinstance(obj,datetime.datetime):#datetime型別轉換,使其可以轉換為json格式資料 return obj.__str__() return super(DecimalEncoder,self).default(obj) class RUNSQL(object): def run_sql(self): db=pymysql.connect(host='伺服器地址',port=3306,user='使用者名稱',password='密碼',db='資料庫名稱',charset='utf8') self.cursor1=db.cursor() self.cursor2=db.cursor() self.cursor1.execute('desc osc_order;')#獲取欄位屬性預設值 self.cursor2.execute("SELECT * FROM osc_order WHERE customer_id='47001930' and status_name in('訂單已收已付') order by created_at DESC") db.close() def sql_test(self): self.run_sql() index=self.cursor1.fetchall() print(index) result=[] row={} for res in self.cursor2.fetchall(): for i in range(len(index)): row[index[i][0]]=res[i] result.append(row) # print(result) for line in result: print(line) print(json.dumps(result,cls=DecimalEncoder,indent=4,ensure_ascii=False,sort_keys=True))#輸出的是字串 # for data in self.cursor.fetchall(): # print(data) if __name__=='__main__': s=RUNSQL() s.sql_test()