我是MySQLdb的新手。我需要从存储在MySQL中的预定义数据库中读取值。我的问题是当收集值时,它们是元组格式,而不是字符串格式。所以我的问题是:有没有办法将元组转换为字符串?
以下是我的代码的详细信息
import MySQLdb
#get value from database
conn = MySQLdb.connect("localhost", "root", "123", "book")
cursor = conn.cursor()
cursor.execute("SELECT koc FROM entries")
Koc_pre = str(cursor.fetchone())
#create a input form by Django and assign pre-defined value
class Inp(forms.Form):
Koc = forms.FloatField(required=True,label=mark_safe('K<sub>OC</sub> (mL/g OC)'),initial=Koc_pre)
#write out this input form
class InputPage(webapp.RequestHandler):
def get(self):
html = str(Inp())
self.response.out.write(html)
输出采用元组格式“Koc =('5',)”,但我希望“koc = 5”。那么有人可以给我一些我应该检查的建议或参考书吗?
提前致谢!
答案 0 :(得分:19)
如果您只是一次检索一个值(即使用cursor.fetchone()获取一列),那么您只需更改代码即可获得元组中的第一个元素。
Koc_pre = str(cursor.fetchone()[0])