Home >>Python Tutorial >Python Mysql Create Database

Python Mysql Create Database

To Create a Database

This is the python mysql create database part of our tutorial. And if you wish to create any particular kind of database in MySQL then you would have to use the “CREATE DATABASE” statement.

Or you can also perform the function of mysql create database with the help of this statement. For example, if you wish to create a database named ‘mydatabase’ then

import mysql.connector

mydb = mysql.connector.connect (

  host=“localhost”

  user=“yourusername”

 passwd=“yourpassword”

)

mycursor = mydb.cursor ( )

mycursor.execute ( “CREATE DATABASE mydatabase”)

  Then you should execute this code. And if no error pops up then that means that you have created your first python database successfully.

To Check If Database Exists

If you wish to check if a particular kind of python database exists or not then you can do that too.

To perform this particular function you will be required to use the “SHOW DATABASE” statement. With the help of this statement, you can find all the existing databases listed.

For example, if you wish to get a list of databases that are present in your system then  

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 )

  You can also choose to make a connection to access a particular kind of python mysql create database. For example, if you wish to connect to the database named ‘mydatabase’ then  

import mysql.connector

mydb = mysql.connector.connect (

  host=“localhost”

  user=“yourusername”

 passwd=“yourpassword”,

 database=“mydatabase”

  If you get an error when you run this example then that means that the database does not exist. With this, we finish the python mysql create database part of our python mysql tutorial.


No Sidebar ads