Signup/Sign In

Python MySQL - Create Database

In this tutorial we will learn how to create a database or how to check if any database exists already in MySQL using Python.

To create the database in MySQL we will use the "CREATE DATABASE" statement.

Python MySQL - CREATE DATABASE

Below we have the basic syntax of the create database statement:

CREATE DATABASE database_name

Now we will create a database named "studytonight". Let us see how we will create it:

Python MySQL - Create Database Example

Let us create a database named "studytonight".Given below is the code snippet for the same:

#for our convenience we will import mysql.connector as mysql
import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "yourusername",
    passwd = "yourpassword"
)

## Now Let us create an instance of 'cursor' class which is used to execute the 'SQL' statements in 'Python'

cursor = db.cursor()

## creating a database called 'studytonight'
## 'execute()' method is used to compile a 'SQL' statement
## below statement is used to create tha 'studytonight' database

cursor.execute("CREATE DATABASE studytonight")

In the case, if the database named "studytonight" already exists then the above code will raise an error.

If there is no error it means the database is created successfully.

Now let us see how we can check all the databases in our system.

Python MySQL - List all Database

We can list down all the databases in MySQL using Python and in that list we can also check if any particular Database is available or not.

To check if any database already exists SHOW DATABASES SQL statement is used.

Let us see how:

To list out all the databases in the system.Below is the code snippet for the same:

#for our convenience we will import mysql.connector as mysql
import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "yourusername",
    passwd = "yourpassword"
)

cursor = db.cursor()

cursor.execute("SHOW DATABASES")

for x in cursor:
  print(x)

The output of the above code will list out all the databases in the system:

('admin_panel',) ('information_schema',) ('mysql',) ('performance_schema',) ('sakila',) ('studytonight',) ('sys',) ('world',) ('xyz',)

As you can see in the code above, we have used Python for loop to iterate over the cursor object and print the names of all the databases found. Similarly, we can compare the name of databases to check if any particular database already exists, before creating it using Python if condition.

So in this tutorial we learned how to create a new database in MySQL using Python and how to list down all the MySQL databases in Python and print them in console.