close
今天為了要撰寫一些給rERP Ajax使用的API,所以用Python Flask寫了一個restful API,雖然過去已經寫過很多Python資料庫處理相關的CASE,但還是上網去查查看有無最新的用法。查到以後,馬上使用看看:
import datetime
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)
cursor.execute(query, (hire_start, hire_end))
for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()
所謂不用則已,一用就掛! 透過這樣的格式,不停地出現MySQL語法使用錯誤的訊息,真的百思不解! 所以只好回歸到之前的語法,用一個SQL命令字串來搞定裡面所有的條件參數! 整個命令當中的字符與文法,也比較接近實際的SQL命令,不像這官方網站的範例,看起來應該加單引號卻沒有家的感覺很不習慣。所以,後來還是用回自己的語法,還真是條條大路通羅馬呢! 呵呵~
看看唄!
##########################################################################################
### function: query the customer basic data from rERP database ###
##########################################################################################
def queryCustId(parSchema, parTable, parVal):
print(parSchema, parTable, parVal)
try:
#create the database conncetion and transaction cursor
dbCon = myCon.getMySQLConnect(parSchema)
dbCur = myCon.getMySQLCursor(dbCon)
#assign the data to each query parameters
strSQL = "SELECT name_ch, comp_id FROM %s WHERE name_ch='%s'"%(parTable, parVal)
dbCur.execute(strSQL)
#------ printing out the customer data from query result
resArray=[]
for row in dbCur:
resArray.append([row['name_ch'], row['comp_id']])
print(resArray)
#------ close all of the DB conncetion
dbCur.close()
dbCon.close()
#print('db closed!')
return [1,resArray]
except (mySQLdb.Error, mySQLdb.Warning) as e:
dbCon.rollback
return [0,'query data failed: '+str(e)]
程序或是函數加上註解表頭,是本人撰寫程式的習慣;對於資料庫的處理上,因為比較critical,所以也是需要加上exception handler會比較嚴謹,未來搭配exception management的管理規則,去記錄所有錯誤的訊息,並對應適當的error code,相信對於產品的嚴謹度會有良好的提升,當然也可以讓產品的品質會更好一點! 給您參考看看囉! ^^
文章標籤
全站熱搜
留言列表