python-mysql-database

Python MySQL – Creation of Database

In This Article, You Will Know About Python MySQL Database.

Python MySQL Database – Before moving ahead, let’s know a bit about Installation of MySQL.

Table of Contents

1. Create Database

To create a database in MySQL, use the “CREATE DATABASE” statement:

Example: Create a database with the name “my_first_database”.

				
					#create a connection

import mysql.connector 
my_database = mysql.connector.connect(host='localhost',
                                      username='your_MySQL_username',
                                      password='your_MySQL_password')
#create database
function = my_database.cursor()
function.execute("CREATE DATABASE my_first_database")
				
			

If the code above was executed without errors then you have established an account database.

2. Check if Database Exists

You can verify whether there is a database in the list by getting a list of databases within your system with the “SHOW DATABASES” statement.

				
					import mysql.connector
my_database = mysql.connector.connect(host='localhost',
                                      username='your_MySQL_username',
                                      password='Your_MySQL_password')

#cursor() method to execute SQL command

function = my_database.cursor()
function.execute("SHOW DATABASES")

#for() loop to see the list of all DATABASES

for database in function:
    print(database)
				
			

As a result, it returned a list of databases created in MySQL server.

Alternatively, you can access the database when making the connection.

				
					import mysql.connector
my_user_details = mysql.connector.connect(host="localhost",
                                          username="your_MySQL_username",
                                          password="Your_MySQL_password",
                                          database="my_first_database")
print(my_user_details)

				
			

If this page is executed with no error, the database “my_first_database” exists in your system, otherwise you will get an error.

If you find anything incorrect in the above-discussed topic and have further questions, please comment below.

Connect on:

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on