Python MySQL – Create Database

Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To connect with MySQL database server from Python, we need to import the mysql.connector interface.

Syntax:

CREATE DATABASE DATABASE_NAME

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing rquired libraries
import mysql.connector
  
dataBase = mysql.connector.connect(
  host ="localhost",
  user ="user",
  passwd ="gfg"
)
  
# preparing a cursor object
cursorObject = dataBase.cursor()
  
# creating database
cursorObject.execute("CREATE DATABASE geeks4geeks")

chevron_right


Output:

python-mysql-create-db



The above program illustrates the creation of MySQL database geeks4geeks in which host-name is localhost, the username is user and password is gfg.

Let’s suppose we want to create a table in the database, then we need to connect to a database. Below is a program to create a table in the geeks4geeks database which was created in the above program.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing required library 
import mysql.connector 
  
# connecting to the database 
dataBase = mysql.connector.connect(
                     host = "localhost",
                     user = "user",
                     passwd = "gfg",
                     database = "geeks4geeks" )  
  
# preparing a cursor object 
cursorObject = dataBase.cursor() 
  
# creating table  
studentRecord = """CREATE TABLE STUDENT ( 
                   NAME  VARCHAR(20) NOT NULL, 
                   BRANCH VARCHAR(50), 
                   ROLL INT NOT NULL,
                   SECTION VARCHAR(5), 
                   AGE INT,
                   )"""
  
# table created
cursorObject.execute(studentRecord)  
  
# disconnecting from server
dataBase.close()

chevron_right


Output:

PYTHON-MYSQL-CREATE-DB1




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.