I want to print out only the value without any brackets or commas or parenthesis. I am using MySQL with python with mysql.connector.
When I run this code I get "(‘esrvgf’,)". But I want to just get "esrvg".
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database ="mydatabase"
)
cursor = mydb.cursor()
sql = "select nick from users where ipaddress = '192.168.1.4'"
cursor.execute(sql)
myresult = cursor.fetchall()
for x in myresult:
print(x)
2
Answers
cursor.fetchall()
returns a list of tuples (see this question), not a string. If you try to print a tuple you Python will add parentheses, and if you try to print a list Python will add brackets. All you need to do is print the first element withx[0]
. Like this:Alternatively, you can use the
*
operator to pass every element of the tuple as a parameter toprint()
. Like this:By using .fetchall() you won’t get a single element returned even if there’s only one, per the documentation:
Therefore, consider using:
Or, if you are certain it’s a single element: