Python MySQL Create Database¶
To create a database in MySQL, use the “CREATE DATABASE” statement:
Note: In MySQL, it’s mandatory to put a semicolon (;) at the end of a statement, which denotes the termination of a query. However, MySQL Connector/Python automatically appends a semicolon at the end of your queries, so there’s no need to use it in your Python code.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd=""
)
mycursor = mydb.cursor()
mycursor.execute("create database itronix")
- To execute a SQL query in Python, you’ll need to use a cursor, which abstracts away the access to database records.
- A query that needs to be executed is sent to cursor.execute() in string format.
Note: If the above code was executed with no errors, you have successfully created a database
Check if Database Exists¶
You can check if a database exist by listing all databases in your system by using the “SHOW DATABASES” statement:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd=""
)
mycursor = mydb.cursor()
mycursor.execute("show databases")
for x in mycursor:
print(x)
You can also verify in browser by opening phymyadmin: http://localhost/phpmyadmin/