Command:
1
import mysql.connector
Output:
C:UsersHarshit_KantPycharmProjectstest1venvScriptspython.exe C:/Users/Harshit_Kant/PycharmProjects/test1/venv/python-db-conn.py
Process finished with exit code 0
Moving on in this article with Python Database Connection let us see the parameters required to connect to the database:
Username- It is simply the username you give to work MySQL server with, the Default username is root.
Password- Password is given by the user when you have installed the MySQL database. I am giving password here as ‘password123’
Host Name- This basically is the server name or IP address on which your MySQL is running, If it is a ‘localhost’, then your IP address is 127.0.0.0
I will show you from a coding perspective to connect python with MySQL database.
Example:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="password123") // I have used 'host','username','password'
print(mydb)
Output:
C:UsersHarshit_KantPycharmProjectstest1venvScriptspython.exe C:/Users/Harshit_Kant/PycharmProjects/test1/venv/python-db-conn.py
mysql.connector.connection_cext.CMySQLConnection object at 0x000001606D7BD6A0
Process finished with exit code 0
Explanation: Here ‘mydb’ is just an instance. From the output, you can clearly see that it has connected to the database.
Next up in Python Database Connection, you will learn how to create a database.
Creating a Database:
Once the database connection is established, you are ready to create your own database which will be acting as a bridge between your python and MySQL server.
Let’s see the implementation part of it.
Example:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="password123")
mycursor=mydb.cursor()
mycursor.execute("create database harshdb")
Output:
C:/Users/Harshit_Kant/PycharmProjects/test1/venv/python-db-conn.py
Process finished with exit code 0
Explanation:
In the above program, I have made use of cursor which is basically an object that is used to communicate to your entire MySQL server through which I am able to create my own database.
You can see from the output that my database with the name”harshdb” is created which is custom, as you can give any name to your database.
If you want to see the databases in your MySQL server, you can implement the following piece of code in pycharm:
Example :
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="password123")
mycursor=mydb.cursor()
mycursor.execute("show databases")
for db in mycursor:
print(db)
Output:
C:UsersHarshit_KantPycharmProjectstest1venvScriptspython.exe C:/Users/Harshit_Kant/PycharmProjects/test1/venv/python-db-conn.py
(‘harshdb’,)
(‘information_schema’,)
(‘mysql’,)
(‘performance_schema’,)
(‘sakila’,)
(‘sys’,)
(‘world’,)