Skip to content
Related Articles

Related Articles

Improve Article

Python MariaDB – Select Query using PyMySQL

  • Last Updated : 14 Oct, 2020

MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python.

In this article we will look into the process of querying data from a table of the database using pymysql.  To query data use the following syntax:

Syntax :

  • In order to select particular attribute columns from a table, we write the attribute names.
 SELECT attr1, attr2 FROM table_name
  • In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol.
SELECT * FROM table_name


Example 1 :

Python3






import pymysql
  
# Create a connection object
# IP address of the MySQL database server
Host = "localhost"  
  
# User name of the database server
User = "user"      
  
# Password for the database user
Password = ""           
  
database = "GFG"
  
conn  = pymysql.connect(host=Host, user=User, password=Password, database)
  
# Create a cursor object
cur  = conn.cursor()
  
  
query = f"SELECT * FROM PRODUCT"
  
cur.execute(query)
  
rows = cur.fetchall()
conn.close()
  
for row in rows :
    print(row)

Output :

querying data in mariadb

output of code

querying data in mariadb

SQL output

The above program illustrates the connection with the MariaDB database ‘GFG‘ in which host-name is localhost, the username is ‘user’ and password is ‘your password’.

Example 2 :

Python3




import pymysql
  
# Create a connection object
  
conn  = pymysql.connect('localhost', 'user', 'password', 'database')
  
# Create a cursor object
cur  = conn.cursor()
  
  
query = f"SELECT price,PRODUCT_TYPE FROM PRODUCT"
  
cur.execute(query)
  
rows = cur.fetchall()
conn.close()
  
for row in rows :
    print(row)

Output :

querying data in mariadbquerying data in mariadb

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :