1.
Python從MySQL資料庫中 用 Select語法 搭配 fetchall()函數 取得的資料,其形態為 tuple
因為程式中要進行邏輯判斷(if...之類的)大多是用String比較方便
所以如何將擷取到的資料轉型成String很重要!!
如我的範例:
import MySQLdb
db = MySQLdb.connect(host="140.115.xxx.xxx", user="xxx", passwd="xxx", db="xxx")
cursor = db.cursor()
cursor.execute("SELECT UDP_Port FROM GA_infor")
udp_port = cursor.fetchall()
for i in udp_port:
print "%s %s" %( i[0][0], i[1][0] )
print "Number of rows returned: %d" % cursor.rowcount
所以變數udp_port的型態就是tuple了,印出來的資料會像是 (('54321',),) 的output
fetchall() returns the entire result set all at once as a tuple of tuples, or as an empty tuple if the result set is empty.
好的,所以要取得字串變數就好的方法為:
=== udp_port[0][0] 即可 === output為54321
簡單吧qq
如果只是 udp_port[0] 那output只會是 ('54321',) 而已唷!!
2.
但是也可以用 fetchall()函數 但是搭配取得的是 dictionaty(字典,所以索引可以用字串來表示) 唷!!
The fetch loops shown thus far retrieve rows as tuples. It's also possible to fetch rows as dictionaries, which enables you to access column values by name.
cursor = conn.cursor (MySQLdb.cursors.DictCursor)
cursor.execute ("SELECT name, category FROM animal")
result_set = cursor.fetchall ()
for row in result_set:
print "%s, %s" % (row["name"], row["category"])
print "Number of rows returned: %d" % cursor.rowcount
3.
用 Python 執行的 SQL語法 中,遇到 UPDATE, INSERT 要記得做 commit 喔!!
db = MySQLdb.connect(host="localhost", user="xxx", passwd="xxx", db="xxx")
cursor = db.cursor()
cursor.execute("update GA_JOIN_Info set outport=%s where Nu=%s", [str(GA_Server_Port[i]) , str(i)])
db.commit()
4.
fetchone() 函數 回傳的是 一維(One dimension)的 tuple, 且 若query後是沒東西的,會回傳None回來~
而回傳的資料是用 [0] 來取出即可。
GA_Port = cursor.fetchone()#tuple
#GA_Port[0][0] is the real value
if GA_Port[0] == None: #fetchone() function, so we can use None to do verifing, and the index is [0], not [0][0]
print("This client didn't do GA yet.")
break; #exit the for-loop
在Python上,安裝 MySQL 的 library:
[1]. 安裝 MySQLdb (因為等等要使用該Module)
sudo apt-get install python-mysqldb
[2]. 測試一下是否可用該module了
#python
import MySQLdb
沒import error就是成功了。
