Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 627
TTT Avatar asked Mar 13 '12 21:03

TTT


People also ask

Can we convert tuple to string in Python?

Create an empty string and using a for loop iterate through the elements of the tuple and keep on adding each element to the empty string. In this way, the tuple is converted to a string. It is one of the simplest and the easiest approaches to convert a tuple to a string in Python.

What does cur Fetchall return?

fetchall() Method. The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

What is MYSQLdb in Python?

What is MYSQLdb? MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2. 0 and is built on top of the MySQL C API.


1 Answers

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]) 
like image 161
Bobby W Avatar answered Oct 20 '22 00:10

Bobby W