Thursday, July 4, 2024
HomeLanguagesPythonCreate Database in MariaDB using PyMySQL in Python

Create Database in MariaDB using PyMySQL in Python

MariaDB is an open source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python.

In this article we will look into the process of creating a database using pymysql. To create a database use the below syntax:

Syntax:CREATE DATABASE databaseName;

Example :

In this example we will be using the pymysql client to create a database named “GFG”:

Python




# import the mysql client for python
  
import pymysql
    
# Create a connection object
# IP address of the MySQL database server
Host = "localhost" 
  
# User name of the database server
User = "user"       
  
# Password for the database user
Password = ""           
  
conn  = pymysql.connect(host=Host, user=User, password=Password)
  
# Create a cursor object
cur  = conn.cursor()
  
# creating database 
cur.execute("CREATE DATABASE GFG"
  
cur.execute("SHOW DATABASES")
databaseList = cur.fetchall()
  
for database in databaseList:
  print(database)
    
conn.close()


Output :

creating database in mariadb

The above program illustrates the creation of MariaDB database “GFG”  in which host-name is ‘localhost‘, the username is ‘user’ and password is ‘your password’.

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 GFG database which was created in the above program.

Example :

Python3




import pymysql
  
conn = pymysql.connect('localhost','user','password','GFG')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS PRODUCT"
query = """CREATE TABLE PRODUCT ( 
         PRODUCT_ID  CHAR(20) NOT NULL, 
         price  int(10), 
         PRODUCT_TYPE VARCHAR(64) ) """
  
# To execute the SQL query
cur.execute(query)   
  
# To commit the changes
conn.commit()         
conn.close()


Output :

adding tables in mariadbadding tables in mariadb

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments