1

I am quite new to coding (I actually started 3 days ago), so please bare with me in case this question is easy to solve.

Here is my problem:

  1. I connected myself to my db and requested data from db using mysql.connector in PyCharm
  2. I want the result to be a plain string and assign this "plain" data to a variable so I can use it later in my code
  3. I do get the result in a different way (is it a list?)

So here is my code:

mycursor = mydb.cursor()

mycursor.execute("select firstname from customer c join application a on a.customerid = c.id where c.id=1;")
firstname = mycursor.fetchall()

print(firstname)

My current output:

[('Max',)]

My expected output:

Max

Any ideas how I can convert firstname to my desired format?

Thanks in advance!

2
  • 1
    hi, perhaps get the first row with fetchone and then get the first column with row[0] Commented Jan 4, 2021 at 19:54
  • thanks for the answer, I only get one value (=firstname), I was wondering how I can remove these characters right and left [('',)] Commented Jan 4, 2021 at 19:57

2 Answers 2

1

If you only need a single row, use mycursor.fetchone() instead of mycursor.fetchall().

The result you're currently getting is a list containing 1 tuple containining 1 string. It can be accessed as firstname = mycursor.fetchall()[0][0]

The better solution is firstname = mycursor.fetchone()[0]

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, also for the explanation. Will do some research on this "tuple" thingy.
0

mycursor = mydb.cursor() Var1 =[] mycursor.execute("select firstname from customer c join application a on a.customerid = c.id where c.id=1;") firstname = mycursor.fetchall() for nameList in firstname:

  nameList.append(firstname)
   

print(nameList)

Try this...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.