2012-03-01 36 views
1

我試圖訪問Django的另一個數據庫(另一個應用程序),並進行了查詢,讓我的Django項目內的一些數據具有以下:蟒蛇(Django的)數據庫返回的結果(u'string')

cursor = connections['another_db'].cursor() 
cursor.execute("query here to fetch data") 
retVal = cursor.fetchone() 

retVal是amysql數據庫中的文本類型值。它回來後,我嘗試用另一個字符串Concat的它:

newString = "%s: %s" % (retVal, anotherString) 
logging.debug("newString: %s" % newString) 

我得到了以下的輸出:

DEBUG:root:newString value: (u'RetValString',): anotherStringValue 

有什麼辦法去除(u' .. ')包裝,因此,只有RetValString: anotherStringValue節目嗎?

回答

0

u'表示retVal實際上是unicode。 (嘗試打印type(retVal))因此,要回答您的問題,您可以通過調用retVal = str(retVal)

+0

我做retVal的= STR(retVal的),然後用 logging.debug打印( 'retVal的:%s' 的%retVal的) 我仍然得到:(u'retValString」,)..任何想法? – triston 2012-03-01 02:34:04

+0

請參閱上面的burhan的回答 - 我沒有注意到retVal在一個元組內。所以對我的代碼示例的修復將會是retVal = str(retVal [0]) - 那就是抓住tupple中的第一個元素並將其轉換爲字符串。但是,您應該閱讀並理解burhan的解釋。 – Aurora 2012-03-01 17:05:25

0

將其轉換爲「常規」字符串。如果文本是用於呈現給用戶的,那麼您應該可以不做任何處理。將它轉換爲一個字符串(使用str())只會有利於將它傳遞給需要字符串的某些內容(如subprocess.Popen)。

3

您的返回值是單個項目序列(元組),而不是字符串。這是從Python DB-API標準:

.fetchone()

 Fetch the next row of a query result set, returning a 
     single sequence, or None when no more data is 
     available. [6] 

     An Error (or subclass) exception is raised if the previous 
     call to .execute*() did not produce any result set or no 
     call was issued yet. 

於是立即解決將是:

newString = "%s: %s" % (retVal[0], anotherString) 

但是,它始終是更好地檢查對於任何返回值:

cursor = connections['another_db'].cursor() 
cursor.execute("query here to fetch data") 
retVal = cursor.fetchone() 
if retVal: 
    newString = "%s: %s" % (retVal[0], anotherString) 

作爲獎勵,你應該將它包裝在try/catch塊中,因爲如果存在任何問題,fetchone會引發異常並且異常。