Skip to content

How to Create a MySQL Database in Python

In order to create a MySQL database in Python, you first need to initiate a connection using the mysql.connector. You can learn about how to create a connection to MySQL here.

How to Create a Database in Python

Creating a database is simple.

First, make sure you have an active connection to your database, and then set a cursor.

Once you have this, issue the execute command to create your database.

import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE your_database")
Code language: Python (python)

How to Check if a MySQL Database Exists in Python

Using a similar connection as described above, execute the SHOW DATABASES query.

import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd" ) mycursor = mydb.cursor() mycursor.execute("SHOW DATABASES") for x in mycursor: print(x)
Code language: Python (python)

How to Connect to a MySQL Database in Python

Now that you know which database to connect to, you can specify it directly in the beginning.

import mysql.connector mydb = mysql.connector.connect( host = "localhost", user = "username", password = "YoUrPaSsWoRd", database="your_database" )
Code language: Python (python)

See also  How to Find an item's Alphabet Position in Python
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x