Saturday , July 27 2024
Python MySQL Select From

Python MySQL Select From

5 Python MySQL Select From

Python MySQL Select From Table

To select from a table in MySQL, use the “SELECT” statement:

In [11]:
import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="itronix"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
    print(x)
(1, 'Karan', 'Ludhiana')
(2, 'Kevin', 'Dublin 4')
(3, 'Keisha', 'Otawa 4')
(4, 'Varun', 'Ontario')
(5, 'Priya', 'Delhi')
(6, 'Atharv', 'Goa')
(7, 'Sia', 'Dubai')

Selecting Columns

  • To select only some of the columns in a table, use the “SELECT” statement followed by the column name(s):
In [12]:
import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="itronix"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name, address FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
    print(x)
('Karan', 'Ludhiana')
('Kevin', 'Dublin 4')
('Keisha', 'Otawa 4')
('Varun', 'Ontario')
('Priya', 'Delhi')
('Atharv', 'Goa')
('Sia', 'Dubai')

Using the fetchone() Method

  • If you are only interested in one row, you can use the fetchone() method.
  • The fetchone() method will return the first row of the result:
In [13]:
import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="itronix"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name, address FROM customers")
myresult = mycursor.fetchone()
print(myresult)
('Karan', 'Ludhiana')

About Machine Learning

Check Also

Python MySQL Insert Into Table

Python MySQL Insert Into Table

4 Python MySQL Insert Into Table Python MySQL Insert Into Table¶To fill a table in …

Leave a Reply

Your email address will not be published. Required fields are marked *