Javaexercise.com

How to create a database in MySql using Python?

Database is a term which is used to refer organized collection of data. Generally, we use DBMS to create and handle database but in some scenario, there can be need for handling database through programming languages. Here, we are creating a database using Python into MySql which is a Relational Database Management System.

Before creating database, we must have MySql and Python language installed in our computer system.

To create a database in MySql, Python provides API and methods that help to execute sql statements. It allows us to use sql queries directly to perform DDL or DML operations such as creating database or table, inserting data into table, updating data or fetching record etc.

Example: Creating Database using Python Script

Below is the Python script that connect to the MySql and create a database.

import mysql.connector
from mysql.connector import errorcode

try:
  
  # Connecting with MySql
  con = mysql.connector.connect(user='db_username', password='mysql_password', host='127.0.0.1')

  # Using cursor() method to create a cursor object
  cursor = con.cursor()

  # Creating a database  
  cursor.execute("create database company")

except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Your user name or password is incorrect")
  else:
    print(err)
else:
  con.close()

After creating database using above Python code, now we can connect to that database to verfiy its existance. Lets connect to database.

Example: Connecting to Created Database

import mysql.connector
from mysql.connector import errorcode

try:
  
  # Connecting with MySql
  con = mysql.connector.connect(user='db_username', password='mysql_password', host='127.0.0.1', database='company')
  print("Connected to database successfuly")	
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Your user name or password is incorrect")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  con.close()

After successful connecting to the database, it will show the message "Connected to database successfuly", else it will show "Database does not exist".


Conclusion

Well, in this topic, we learnt about creating a database into MySql using Python script and successfuly connected to that database. 

In our next topic, we will learn to create table inside this database. Till then keep learning and practice.