gpt4 book ai didi

python (django) 数据库返回结果 (u'string')

转载 作者:搜寻专家 更新时间:2023-10-30 22:17:28 25 4
gpt4 key购买 nike

我正在尝试访问 django 中的另一个数据库(另一个应用程序),并使用以下查询在我的 django 项目中获取一些数据:

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

retVal是amysql数据库中的一个文本类型的值。返回后,我尝试将其与另一个字符串连接:

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

我得到了以下输出:

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

有什么方法可以删除 (u' .. ') 包装器,以便只显示 RetValString: anotherStringValue 吗?

最佳答案

您的返回值是单个项目序列(元组),而不是字符串。这是 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 block 中,因为如果有任何问题,fetchone 将引发异常。

关于python (django) 数据库返回结果 (u'string'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9509194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com