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 :
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 :