0

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".

enter image description here

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 Answers2

1

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 with x[0]. Like this:

for x in myresult:
  print(x[0])

Alternatively, you can use the * operator to pass every element of the tuple as a parameter to print(). Like this:

for x in myresult:
  print(*x)
Michael M.
  • 10,486
  • 9
  • 18
  • 34
0

By using .fetchall() you won't get a single element returned even if there's only one, per the documentation:

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.

Therefore, consider using:

for x in myresult:
  for y in x:
     print(x)

Or, if you are certain it's a single element:

for x in myresult:
   print(x[0])
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53