Create a MySQL Database in Python


With the intention to create a MySQL database in Python, you first must provoke a connection utilizing the mysql.connector. You’ll be able to study learn how to create a connection to MySQL right here.

Create a Database in Python

Making a database is easy.

First, be sure to have an lively connection to your database, after which set a cursor.

After getting this, problem the execute command to create your database.

import mysql.connector

mydb = mysql.connector.join(
  host = "localhost",
  person = "username",
  password = "YoUrPaSsWoRd"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE your_database")

Verify if a MySQL Database Exists in Python

Utilizing an identical connection as described above, execute the SHOW DATABASES question.

import mysql.connector

mydb = mysql.connector.join(
  host = "localhost",
  person = "username",
  password = "YoUrPaSsWoRd"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW DATABASES")

for x in mycursor:
  print(x)

Hook up with a MySQL Database in Python

Now that you realize which database to connect with, you possibly can specify it immediately to start with.

import mysql.connector

mydb = mysql.connector.join(
  host = "localhost",
  person = "username",
  password = "YoUrPaSsWoRd",
  database="your_database"
)
See also  Methods to Sum all of the Integers in a String in Golang

Leave a Reply