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.
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
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.