Python MySQL Create Database


One or more tables comprise a database.

To create or delete a MySQL database you require special permissions.


Create MySql Database

You must have basic knowledge of SQL query to work with mysql database.

The following queries are used to create a database in mysql:

CREATE DATABASE database_name

The following queries are used to delete a database in mysql:

DROP DATABASE database_name

Creating a Database

The mysql.connector.connect() method is used to connect to a Mysql database.

It takes few arguments like host, username, password, database and etc.

Use the statement CREATE DATABASE to build a database in MySQL:

Example :- create a database named "mydatabase" :

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  password="mypassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

print("Database created successfully!")

Output :-

Database created successfully!

If no errors have been found in the given code, you have created a database successfully.

You can also search for these topics, python mysql can't create database, create database mysql python best practices, how to blank the python database, mysql database to create a python generator, mysql create memory in python database, python list the mysql create database options, Example for Python MySQL Create Database.

Check if Database Exists

By identifying all databases within your system you can check if the database exists with the statement "SHOW DATABASES" :

Example 1 :- Return a list of your system's databases :

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  password="mypassword"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
  print(x)

Output :-

('information_scheme',)
('mydatabase',)
('performance_schema',)
('sys',)

Otherwise while initiating a connection, you might attempt accessing the database :

Example 2 :- Try connecting to the database "mydatabase" :

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  password="mypassword",
  database="mydatabase"
)

print("Database exists")

Output :-

Database exists

Note :- You will get an error if the database isn't there.

You can also search for these topics, python check if database exists and not empty, create the existing of database using python, python use the database exist entry, check the global function and number to python existing of python, python value to exists with open in existing database.