Create database in MySQL using Python




In this post, we will see how to create database using python in MySQL.

Creating the Database

To create the database, we need to import the mysql.connector interface.

The SQL Command to create a database is

CREATE DATABASE DATABASE_NAME

The below program shows the creation of MySQL database onecompiler in which hostname is localhost, and the username is test and password is password.

# importing the required package 
import mysql.connector 

db = mysql.connector.connect( 
host ="localhost", 
user ="test", 
passwd ="password"
) 

# preparing a cursor object 
cursorObject = db.cursor() 

# creating the database 
cursorObject.execute("CREATE DATABASE onecompiler") 

Creating a table

Suppose you want to create a table inside the database you created, follow the below steps:

# importing required library 
import mysql.connector 

# connecting to the database 
db = mysql.connector.connect( 
					host = "localhost", 
					user = "test", 
					passwd = "password", 
					database = "onecompiler" ) 

# preparing a cursor object 
cursorObject = db.cursor() 

# creating the table 
userTable = """CREATE TABLE USERS ( 
				NAME VARCHAR(20) NOT NULL, 
				BRANCH VARCHAR(50), 
				AGE INT, 
				)"""

# table created 
cursorObject.execute(userTable) 

# disconnecting from server 
db.close()