Python MySQL - Create Database
You can create a database in MYSQL using the CREATE DATABASE query.
Syntax
Following is the syntax of the CREATE DATABASE query −
CREATE DATABASE name_of_the_database
Example
Following statement creates a database with name mydb in MySQL −
mysql> CREATE DATABASE mydb; Query OK, 1 row affected (0.04 sec)
If you observe the list of databases using the SHOW DATABASES statement, you can observe the newly created database in it as shown below −
mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | details | | information_schema | | jpadb | | mydb | | mysql | | performance_schema | | sys | | test | | tutorials | | tutorialspoint | +--------------------+ 10 rows in set (0.00 sec)
Creating a database in MySQL using python
After establishing connection with MySQL, to manipulate data in it you need to connect to a database. You can connect to an existing database or, create your own.
You would need special privileges to create or to delete a MySQL database. So if you have access to the root user, you can create any database.
Example - Creating a Database
Following example establishes connection with MYSQL and creates a database in it.
main.py
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Dropping database MYDATABASE if already exists.
cursor.execute("DROP database IF EXISTS MyDatabase")
#Preparing query to create a database
sql = "CREATE database MYDATABASE";
#Creating a database
cursor.execute(sql)
#Retrieving the list of databases
print("List of databases: ")
cursor.execute("SHOW DATABASES")
print(cursor.fetchall())
#Closing the connection
conn.close()
Output
List of databases:
[('details',), ('information_schema',), ('jpadb',), ('mydatabase',), ('mydb',), ('mysql',), ('performance_schema',), ('sys',), ('test',), ('tutorials',), ('tutorialspoint',)]
Advertisements