How to Query from MySQL Database in Python

with No Comments

Link: https://www.w3schools.com/python/python_mysql_select.asp

fetch-all()

import mysql.connector
mydb = mysql.connector.connect (
  host="localhost",
user="yourusername",
  password="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
  print(x)
fetchone()
import mysql.connector
mydb = mysql.connector.connect (
  host="localhost",
user="yourusername",
  password="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
for x in myresult:
  print(x)
I also did notice something quite peculiar when I printed out the data received from fetchone() or fetchall(). It seemed to be a tuple format, and when I tried to index for each element of the data or indexing for each element (such as data[0]), I received it in this format: (‘entry’,) which was difficult to parse. Therefore, I had to parse again just for the first element: data[0][0] to get the actual entry and data from the database I needed.
Note: This only works if you are searching for 1 column.

Leave a Reply