Google News
logo
Python Program to Create a database in MySQL
To create a database in MySQL using Python, you can use the `mysql-connector-python` module which provides a Python interface to MySQL. Here's an example Python program that creates a database in MySQL :

Syntax :
import mysql.connector

# Create a connection to the MySQL server
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

# Create a cursor object to execute SQL statements
mycursor = mydb.cursor()

# Create a database
mycursor.execute("CREATE DATABASE mydatabase")

# Print a message to indicate the database has been created
print("Database created successfully!")​
In the above example, the `mysql.connector` module is imported at the beginning of the program. The `connect()` function is then called to create a connection to the MySQL server. You will need to replace `yourusername` and `yourpassword` with your MySQL username and password.

Next, a cursor object is created using the `cursor()` method of the connection object. This cursor object can be used to execute SQL statements on the database.

In this example, the program creates a database named `mydatabase` using a SQL `CREATE DATABASE` statement.

After the database has been created, the program prints a message to indicate that the database has been created successfully.

Finally, the connection is closed using the `close()` method of the connection object. Note that the `close()` method is not called in this example, but you should always close the connection when you are finished with it to free up resources.