Pymysql库不会在数据库中返回纯数据

时间:2017-07-31 12:09:09

标签: python mysql sql python-3.x pymysql

我是Python新手,特别是 pymysql 库。

我想从我的数据库进行查询,当查询完成时,结果不是数据库中的纯记录,并且有一些括号和“,”标记等。

这是我的代码。

如果你回答我,我会很感激

from pymysql import *
def database_connector():
db = connect(host="localhost",port=3306,user="root",passwd="", 
db='telegrambot',charset='utf8')
return db
def question_return(tests_id,questions_id):
db=database_connector()
cursor=db.cursor()
cursor.execute("""SELECT question FROM questions WHERE test_id = '%s' AND 
question_id = '%s';""",(tests_id,questions_id))
return_value = cursor.fetchall()
return return_value

print (question_return(1,1))

它打印出这样的东西。

(('What is your name ?',),)

我想在没有括号和其他标记的情况下打印这样的东西

What is your name ?

请帮我怎么做

非常感谢

2 个答案:

答案 0 :(得分:0)

由于它返回元组的元组,你必须迭代它。找到以下代码。

from pymysql import *
def database_connector():
    db = connect(host="localhost",port=3306,user="root",passwd="", 
    db='telegrambot',charset='utf8')
    return db
def question_return(tests_id,questions_id):
    db=database_connector()
    cursor=db.cursor()
    cursor.execute("""SELECT question FROM questions WHERE test_id = '%s' AND 
    question_id = '%s';""",(tests_id,questions_id))
    return_value = cursor.fetchall()
    return return_value

for r in question_return(1,1):
    print r[0]

答案 1 :(得分:0)

将游标类声明为数据库连接器声明

from pymysql import *

def database_connector():
    db = connect(
        host="localhost",
        port=3306,
        user="root",
        passwd="", 
        db='telegrambot',
        charset='utf8'
        cursorclass=pymysql.cursors.DictCursor # <-- declare cursor class
    )
return db

def question_return(tests_id,questions_id):
    try:
        with database_connector() as cursor
            query = "SELECT question FROM questions WHERE test_id = '%s' AND question_id = '%s';"
            cursor.execute(query, (tests_id,questions_id))
            return cursor
    finally:
        database_connector().close()

with question_return(1,1) as pointer:
    for row in pointer.fetchall():
        print(row['question'])