×

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 Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Python Tricks: The Book

A Buffet of Awesome Python Features Dan Bader is the author of the book called Python Tricks . he is the owner and editor of Real Python and one of the...

3 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

Python Struct

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Python Data Visualization

In this tutorial, we will understand what data visualization means in python. Further, we will see different methods of visualizing data in python. Data visualization In a non-technical language, it is a...

4 minutes read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Spell Corrector GUI using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.