Home >>Python Tutorial >Python MySQL – Select From Table

Python MySQL – Select From Table

Select from a Table

This is the python mysql select query module of the Python MySQL tutorial. And if you wish to select a particular table from MySQL in this programming language then you can do that. To accomplish that task you will be required to use the “SELECT” statement. For example, if you wish to select all the particular records from the table named ‘customer’ and then if you want to display the result then  

import mysql.connector

mydb = mysql.connector.connect (

  host=“localhost”

  user=“yourusername”

 passwd=“yourpassword”

 database=“mydatabase”

)

mycursor = mydb.cursor ( )

mycursor.execute (“SELECT * FROM customers”)

myresult = mycursor.fetchall ( )

for x in mycursor :

  print ( x )

  The fetchall ( ) method that is mentioned above is used to fetch all the particular rows from the statement that was executed last in this programming language.  

To Select Columns

If you wish to only select some of the columns that are present in a table then you can do that too. To accomplish that task you need to use the ‘SELECT’ statement. Once you mentioned this statement then you shouldn’t forget to follow it by the name of the column or the names of the column that you wish to select. If you wish to select the address and the name column then the python mysql select example for this is mentioned below.  

import mysql.connector



mydb = mysql.connector.connect (

  host=“localhost”

  user=“yourusername”

 passwd=“yourpassword”

 database=“mydatabase”

)



mycursor = mydb.cursor ( )



mycursor.execute (“SELECT name, address FROM customers”)



myresult = mycursor.fetchall ( )



for x in mycursor :

  print ( x )

 

To Use the Fetachone ( ) Method

If you wish to fetch only a single row from a particular table then we suggest that you should use the fetchone ( ) method. If you use this method then it is important for you to remember that as the result of this method you will only be returned with the first row of the entire table. The python mysql select example for this is mentioned below.  

import mysql.connector



mydb = mysql.connector.connect (

  host=“localhost”

  user=“yourusername”

 passwd=“yourpassword”

 database=“mydatabase”

)



mycursor = mydb.cursor ( )



mycursor.execute (“SELECT * FROM customers”)



myresult = mycursor.fetchone ( )



print ( myresult )

  With this, we finish the python mysql select query part of our entire Python MySQL tutorial.


No Sidebar ads