2012-03-01 33 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会引发异常并且异常。