Connecting python to database - Letsprogram

Share:
Python is used in database applications. When discussing famous databases some are MySQL, Oracle, Microsoft SQL Server and etc.

The database is very useful to store the information so we connect the database with the programming language. In our case, it is the python to connect database with any programming language we should install a related driver given by the database company

connecting python with database


In this case, we gonna take MySQL as our database but to connect the database to our programming language it should be in our system or the server. If you do not have any database in your system download the MySQL installer

After, installing the MySQL database in your system then install the MySQL driver. python needs the MySQL driver to access the MySQL database and it is the same in any other database case we should install related drivers to access the related database.

The driver which we should use to access the database is "MySQL connector"  to install MySQL connector use pip command in the prompt.

pip install mysql-connector

After the command execution, the MySQL connector is downloaded and installed.

import mysql.connector

If this line is executed in the python interpreter then it was successfully installed.
After importing the driver into your program then we have to connect with the database by using the method connect() from the MySQL-connecter it takes parameters like username, password, IP address and database name.

db = mysql.connector.connect(
     host="localhost", 
     user="python",
     passwd="1234"
     database="databasename")

To know more about the MySQL connector for python check this link: https://dev.mysql.com/doc/relnotes/connector-python/


Here are  two small programs on how to access the database with python


execute statement takes the SQL commands used in the respective database.

No comments

F