×

Creating new Database using Python MySQL

In this article, we are going to discuss how to create a new database by connecting Python and MySQL.

What is a Database?

The places or memory used to secure highly and store the data which can be retrieved or modified later. All the databases are managed by particular systems known as Database Management systems in which one of the languages is MySQL.

MySQL is a Structured Query language, whereas Python is a Programming language. We are supposed to merge these two different languages in order to create a new database using Python and MySQL. In Java, we have inbuilt drivers, which by default, form a bridge between the Programming language ( java ) and the Structured Query language. In python, we need to import the required drivers that can support MySQL and Python.

Let us understand the concept of creating a database using Python and MySQL by following the steps mentioned below.

Step-by-step procedure for creating a Database using Python and MySQL:

  1. Install MySQL
  2. Connect Python to MySQL server using the required database notations
  3. Create a database
  4. Close the connectivity to the MySQL server

Install MySQL

In order to initiate access for Python to the database, we need to install MySQL so that it forms a connective bridge between Python and the databases.

We import all the characteristics of the MySQL server using the " MySQL connector " driver. The driver " MySQL connector " is used to grant permissions for python to access the database. Install the " MySQL connector " driver and import it to python.

Syntax to import MySQL through “ MySQL connector “ driver:

# import the driver “ MySQL connector “ initially
import mysql.connector

The above line imports all the members of MySQL into Python. Having zero errors is an indication of successful installation and import of MySQL.

Connect Python to MySQL server using the required database notations

As soon as the installation and importing of MySQL is completed, we are supposed to connect the system and MySQL databases by giving all the information of the admin user, including the password.

The syntax for arranging a connection between the system and MySQL databases using Python:

# import the driver “ MySQL connector “ initially
import mysql.connector


# the database “ data_base “ is being used to create a connection within the current user and MySQL server and then waiting for the required permissions from the admin user
data_base = mysql.connector.connect(
    user = " name of the current admin user "
    password = " password of the current admin user "
    host = " localhost "
)
# printing the database connectivity with python
print(data_base)

This program prints the credentials created using the " data_base ". The connection between the user and the server is made after the above step. Hereafter, you can specify the queries using a few methods. Those methods shall be discussed below.

Query to create a new database:

CREATE DATABASE name_of_new_database;

The syntax to create a new Database:

# syntax for creating a new database 
database_query = " CREATE DATABASE name_of_new_database " 

This query and line of code are used to create a new database. But, in Python, queries are not considered to be actual queries. They need to be converted into a string, and after that, they are reconsidered to be SQL queries. To handle this, we need to use the " cursor() “ and “ execute() “ methods.

The cursor() method is used to gain access to the required existing database or newly created databases. After the specific database is mentioned, the cursor() method grants access to that particular database. Let us understand the cursor() method in detail.

Cursor method [ cursor() ]:

The method “ cursor() “ supposes to be an access giver or an access mediator. An object is created, which is also an instance of MySQLcursor class. This object is used to call its method, i.e., the cursor method.

The syntax of cursor() method and creating cursor object:

# creating an instance of MySQLcursor class and calling the cursor method using that object
cursor = connection.cursor()

As we have already discussed, a query is not initially considered to be a query unless the " execute() " method is introduced. The purpose of the execute method is that it converts the query initially into a string and then receives it as a database query.

Let us have a look at a complete general program where we can create a new database:

# import the driver “ MySQL connector “ initially
import mysql.connector


# the database “ data_base “ is being used to create a connection within the current user and MySQL server and then waiting for the required permissions from the admin user
data_base = mysql.connector.connect(
    user = " name of the current admin user "
    password = " password of the current admin user "
    host = " localhost "
)
# creating an instance of MySQLcursor class and calling the cursor method using that object
cursor = connection.cursor()


# syntax for creating a new database 
database_query = " CREATE DATABASE name_of_new_database " 


# linking the statement “ database_query “ to the cursor to convert into a string and then identify that particular string as a query
cursor.execute(database_query)

An explanation of the program mentioned above:

In order to access MySQL, we have imported everything from MySQL using the " mysql.connector " driver. After that, we initiated a connection between the MySQL databases and the system by taking all permissions from the system's admin in order to access its own databases. The username and password of the admin user should be given within the database area.

A connection is established using the " cursor() “ method and instance of MySQLcursor class. The SQL query for creating a new database is set to the " database_query ". After the implementation of the execute() method, the query is taken as a string at first and then considered to be an SQL query. A new database with the name " name _ of _ new _ database " is created.

Close the connectivity to the MySQL server

The program runs even without closing the access to the databases. But, after completing our work, if the access is left without closing, unnecessary and unauthorized access can take place, which might sometimes lead to the deletion of the entire data in the present database. In order to avoid these issues, we must close the connectivity using the " close() " method.

The syntax of close() method:

# to close the connectivity or access to the specific database
database_name.close()

Let us implement this close() method in the above program.

# import the driver “ MySQL connector “ initially
import mysql.connector


# the database “ data_base “ is being used to create a connection within the current user and MySQL server and then waiting for the required permissions from the admin user
data_base = mysql.connector.connect(
    user = " name of the current admin user "
    password = " password of the current admin user "
    host = " localhost "
)
# creating an instance of MySQLcursor class and calling the cursor method using that object
cursor = connection.cursor()


# syntax for creating a new database 
database_query = " CREATE DATABASE name_of_new_database " 


# linking the statement “ database_query “ to the cursor to convert into a string and then identify that particular string as a query
cursor.execute(database_query)


# to close the connectivity and access to the specific database
data_base.close()

After implementing the close() method, the particular database, i.e., the database with the name “ database_name “ is closed temporarily unless and until we connect to that database again by following all the above steps. 

Let us see an example program that covers all the concepts discussed:

# import the driver “ MySQL connector “ initially
import mysql.connector


# the database “ data_base “ is being used to create a connection within the current user and MySQL server and then waiting for the required permissions from the admin user
data_base = mysql.connector.connect(
    user = " scott "
    password = " tiger "
    host = " localhost "
)
# creating an instance of MySQLcursor class and calling the cursor method using that object “ my_cursor “
my_cursor = connection.cursor()


# syntax for creating a new database 
query = " CREATE DATABASE Hello " 


# linking the statement “ query “ to the cursor to convert it into a string and then identify that particular string as a query
my_cursor.execute(query)


# to close the connectivity and access to the specific database
data_base.close()

The above program creates a database with the name " Hello " and closes the connection after the creation. This is how databases are created using Python and MySQL. You can also insert data, remove data, and modify the data in the databases ( newly created ones or already existing ones ) by using different SQL queries but with the same process.


Related Topics

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

How to make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.

Struct Module in Python

What is a structure in Python? An entity that holds data in form of a structure is called a data structure. In Python, the data structure includes tuples, lists, dictionaries, and...

4 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

Python callable() Function

Python callable() Function The callable() function returns a boolean value ‘True’ if the specified object is callable, else it returns False. Syntax callable(object) Parameter Object:  The object parameter represents the value to test if it is callable...

1 minute read.

Python input() function

Python input() function The input() function in Python reads a line from input and converts it to a string (stripping a trailing newline). Syntax input([prompt]) Parameter prompt: This function represents a string, depicting a default...

1 minute read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Python Pickle

The pickle is a module that enables serialization and de-serialization of the structure of the object in python. Pickling is the process that uses the protocols to convert the Python...

5 minutes read.

GUI to Shut down, Restart and Logout from the PC using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

4 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Difference between python list and tuple

In this tutorial, we will understand the key differences between python lists and tuples in python. Firstly, let us see the similarities between Lists and Tuples. Both are two data types...

4 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.