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 :-
If no errors have been found in the given code, you have created a database successfully.
Related Links
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 :-
('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 :-
Note :- You will get an error if the database isn't there.
Related Links