python MySQL create
To create a new MySQL database using Python, you can use one of the available MySQL libraries in Python. Here, we will use the "mysql-connector-python" library, which is a pure Python implementation of the MySQL client protocol.
To create a new database using "mysql-connector-python" in Python, you will need to follow these steps:
Install the mysql-connector-python library using pip. You can use the following command to install it:
pip install mysql-connector-python
Import the mysql.connector module in your Python script. You can do this using the following code:
import mysql.connector
Establish a connection to your MySQL server using the mysql.connector.connect() method. This method takes several parameters, including the host name, user name, password, and database name. Here is an example:
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
Once you have established a connection, you can create a new database using the "CREATE DATABASE" SQL statement. You can do this by creating a new cursor object using the connection object and executing the SQL statement. Here is an example:
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
Finally, you can check if the database has been created successfully by executing a SHOW DATABASES statement. Here is an example:
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
The complete Python code to create a new database using mysql-connector-python would look like this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
In this code, you will need to replace "yourusername" and "yourpassword" with the actual values for your MySQL server. Once you run this code, it will create a new database called "mydatabase" and print out a list of all the available databases on the server.