Python Create Database
- Previous Page MySQL Basics
- Next Page MySQL Create Table
Create Database
To create a database in MySQL, please use the "CREATE DATABASE" statement:
Example
Create a database named "mydatabase":
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mydatabase")
If there are no errors when executing the above code, then you have successfully created the database.
Check if the database exists
You can list all the databases in the system using the "SHOW DATABASES" statement and check if the database exists:
Example
Return the list of databases in the system:
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword" ) mycursor = mydb.cursor() mycursor.execute("SHOW DATABASES") for x in mycursor: print(x)
Or you can try to access the database when establishing the connection:
Example
Attempt to connect to the database "mydatabase":
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" )
An error will be received if the database does not exist.
- Previous Page MySQL Basics
- Next Page MySQL Create Table