TTT
TTT

Reputation: 4434

Convert MySQLdb return from tuple to string in Python

I am new to MySQLdb. I need to read values from a pre-defined database which is stored in MySQL. My problem is when values are collected, they are in tuple format, not string format. So my question: Is there a way to convert tuple to string?

Below are the details of my code

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)

The output is in tuple format "Koc=('5',)", but I want "koc=5". So can anyone give me some suggestions or reference book I should check?

Thanks in advance!

Upvotes: 8

Views: 16453

Answers (1)

Bobby W
Bobby W

Reputation: 875

If you're only going to be retrieving one value at a time (i.e. getting one column using cursor.fetchone()), then you can just change your code so that you get the first element in the tuple.

Koc_pre = str(cursor.fetchone()[0]) 

Upvotes: 21

Related Questions