SELECT query in MySQL using Python




In this post, we will find how to use the SELECT query in MySQL in Python.

Connecting to database

First, we need to connect to our database,

import mysql.connector 

mydb = mysql.connector.connect( 
host = "localhost", 
user = "username", 
password = "password", 
database = "database_name"
) 

mycursor = mydb.cursor() 

This code will connect to our database.

SELECT query

In order to select particular columns from a table, we write the attribute names.

SELECT name FROM users

Program to select a query from the table in the database using Python.

import mysql.connector 
	
# connecting to the database 
db = mysql.connector.connect( 
					host = "localhost", 
					user = "username", 
					passwd = "password", 
					database = "students" ) 
	
mycursor = dataBase.cursor() 
	
# select query 
query = "SELECT name FROM users"
mycursor.execute(query) 

myresult = mycursor.fetchall() 

for i in myresult: 
	print(i) 

# closing from server 
db.close()