Menu Close

Python MySQL Create Database

python MySQL create database

In this Python MySQL creates database tutorial, we are going to learn all about how to create a database in MySQL.
In the previous tutorial, we have seen the complete process to install MySQL connectors in Python and how to connect them to the MySQL database, Click here to learn.

In the python MySQL create database guide, we will go through how to create a MySQL database using MySQL connector in Python, and also we will see how to show all the databases.

Make sure you have already installed MySQL connector in your machine using pip.
Let’s see how to create a database in MySQL using Python.

Table of Contents

Python MySQL Create Database:

As we know that, MySQL provides “CREATE DATABASE” to create a new database in the MySQL database.

Example:

Here we will create a database named “demodb“.

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="username",
	password="password",
        port = port number
	
)

cursor = mydb.cursor()
cursor.execute("CREATE DATABASE demodb")
print("Database created successfully...")

Output:

Database created successfully...

Check Database exist:

To check the above database create successfully or not, you have to use MySQL “SHOW DATABASES” statement.

Example:

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="username",
	password="password",
        port = port number
	
)

cursor = mydb.cursor()
cursor.execute("SHOW DATABASES")
for db in cursor:
	print(db)

Output:

('college',)
('demodb',)
('information_schema',)
('mysql',)
('mysqldjango',)
('performance_schema',)
('sakila',)
('sys',)
('world',)

The above output may be different in your case.

Connect to database:

After creating the database successfully, you can connect to the database.

Example:

import mysql.connector
mydb = mysql.connector.connect(

	host="localhost",
	user="username",
	password="password",
        port = port number
        database = "data base"
	
)

print("Connection successfully...")

Output:

Connection successfully…

Conclusion

In this Python MySQL Create Database tutorial, you have learned all about how to create a database in MySQL using Python.


MySQL connector is the best for connecting Python applications to the MySQL database and executes SQL queries. After created of database successfully, you can perform a query on that particular database.

If this article for you, please share and keep visiting for further Python MySQL database tutorials.

For more information:- Click Here

Thanks for reading…

Previous Article
Next Article

Related Posts