Reputation: 493
I am trying to access another database (another application) in django, and make a query to get some data within my django project with the following:
cursor = connections['another_db'].cursor()
cursor.execute("query here to fetch data")
retVal = cursor.fetchone()
The retVal
is a text-type value in amysql database. After it's returned, I try to concat it with another string:
newString = "%s: %s" % (retVal, anotherString)
logging.debug("newString: %s" % newString)
I got the following output:
DEBUG:root:newString value: (u'RetValString',): anotherStringValue
Is there any way to remove the (u' .. ')
wrapper, so that only RetValString: anotherStringValue
shows?
Upvotes: 1
Views: 4076
Reputation: 174662
Your return value is a single item sequence (a tuple), not a string. This is standard from the 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.
So the immediate fix would be:
newString = "%s: %s" % (retVal[0], anotherString)
But, its always better to check for any return values:
cursor = connections['another_db'].cursor()
cursor.execute("query here to fetch data")
retVal = cursor.fetchone()
if retVal:
newString = "%s: %s" % (retVal[0], anotherString)
As a bonus, you should wrap it in a try/catch block since fetchone will raise and exception if there are any problems.
Upvotes: 3
Reputation: 2472
If the text is for presentation to a user, you should probably do nothing with it. Converting it to a string (using str()) would only be beneficial if you were passing it to something (like subprocess.Popen) that required a string.
Upvotes: 0
Reputation: 4414
The u'
indicates that retVal is in fact unicode. (Try printing type(retVal)
)So to answer your question you can convert it to a 'regular' string by calling retVal = str(retVal)
Upvotes: 0