Creating MySQL Database

To create a database, we will use CREATE DATABASE database_name statement and we will execute this statement by creating an instance of the ‘cursor’ class.

Python3




import mysql.connector
 
mydb = mysql.connector.connect(
    host = "localhost",
    user = "yourusername",
    password = "your_password"
)
 
# Creating an instance of 'cursor' class
# which is used to execute the 'SQL'
# statements in 'Python'
cursor = mydb.cursor()
 
# Creating a database with a name
# 'w3wiki' execute() method
# is used to compile a SQL statement
# below statement is used to create
# the 'w3wiki' database
cursor.execute("CREATE DATABASE w3wiki")


Output:

If the database with the name ‘w3wiki’ already exists then you will get an error, otherwise no error. So make sure that the new database that you are creating does not have the same name as the database already you created or exists previously. Now to check the databases that you created, use “SHOW DATABASES” – SQL statement i.e. cursor.execute(“SHOW DATABASES”)

Python3




import mysql.connector
 
mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    password = "1234"
)
 
# Creating an instance of 'cursor' class
# which is used to execute the 'SQL'
# statements in 'Python'
cursor = mydb.cursor()
 
# Show database
cursor.execute("SHOW DATABASE")
 
for x in cursor:
  print(x)


Output:

How to Connect Python with SQL Database?

Python is a high-level, general-purpose, and very popular programming language. Basically, it was designed with an emphasis on code readability, and programmers can express their concepts in fewer lines of code. We can also use Python with SQL. In this article, we will learn how to connect SQL with Python using the ‘MySQL Connector Python module. The diagram given below illustrates how a connection request is sent to MySQL connector Python, how it gets accepted from the database and how the cursor is executed with result data.

SQL connection with Python

Similar Reads

Connecting MySQL with Python

To create a connection between the MySQL database and Python, the connect() method of mysql.connector module is used. We pass the database details like HostName, username, and the password in the method call, and then the method returns the connection object....

Creating MySQL Database

...

Creating Tables

To create a database, we will use CREATE DATABASE database_name statement and we will execute this statement by creating an instance of the ‘cursor’ class....