Programming with Python

  1. Home
  2. Docs
  3. Programming with Python
  4. Database in Python
  5. Executing Queries

Executing Queries

Relational Database Management system RDBMS is an application software for creating and managing relational databases. It makes us possible for us to create, read, update and delete data from a database.

MySQL is a popular RDBMS software which use a client server model. So here we will see how to connect database in python.

MySQL, is an open source relational database management system. It is based on the structure query language (SQL), which is used for adding, removing, and modifying information in the database.

Installation of MySQL:-

  • Open the command prompt
  • Type the following command.
  • pip install MySQL -python
  • Successfully install MySQL database.

You can easily import MySQL in python and use it.

syntax:-

import MySQLdb

We can create a new table by importing mysql.connector. To create a database in MySQL, we can use the “CREATE DATABASE” statement. Before that, we need to import mysql.connector and provide the required connection.

There are the following steps to connect a python application to our database.

  • Import mysql.connector module
  • Create the connection object.
  • Create the cursor object
  • Execute the query

syntax:-

import mysql.connector
db_connection = mysql.connector.connect
(    host="hostname",
     user="root", 
     password="pin",
     database="name_of_database"
)
mycursor.execute(SELECT * FROM table)
a=mycursor.fetchall()
print(a)

We have some function which has some specific work:-

  • cursor.execute()- This is used to execute SQL queries.
  • cursor.close()- It is used to close the cursor object.
  • connection.close()- It is used to close MySQL database after the work is done

There are two more function to execute queries:-

  • fetchall()- It fetches all the rows of the result.
  • fetchone()- It only fetches the first row of the result.

This is how we can execute queries in python.

Was this article helpful to you? Yes No

How can we help?