In Python, create a `table` in the MySQL database and manipulate the data using Python programming language. we need to install the "mysql-connector-python" module.
First, we need to install "pip" if haven't installed it already.
Here's how we can Create a Table in the Mysql Database using Python using the "mysql-connector-python" library:
After installing the package, we can use it to establish a connection to our MySQL database and perform operations.
pip install mysql-connector-python
Import `mysql.connector` library and create a configuration object with keys such as `user`, `password`, `host`, and `database`.
# import mysql connector library import mysql.connector # Configuration parameters config = { 'user': 'your_username', 'password': 'your_password', 'host': 'localhost', # or your host address 'database': 'your_database_name', }
Create Table Structure within triple quotes string """ """ and with the help execute() method we can run operation to create a table in MySQL database.
# Define the table query creation create_table_query = """ CREATE TABLE IF NOT EXISTS your_table_name ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT ) """ # Execute the table creation query cursor.execute(create_table_query) print("Table created successfully")
Don't forget to close the connection once done using the "close()" method.
finally: if 'connection' in locals() and connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")
import mysql.connector # Configuration parameters config = { 'user': 'your_username', 'password': 'your_password', 'host': 'localhost', # or your host address 'database': 'your_database_name', } try: # Establish a connection to the MySQL server connection = mysql.connector.connect(**config) if connection.is_connected(): # Create a cursor object to execute SQL queries cursor = connection.cursor() # Define the table creation query create_table_query = """ CREATE TABLE IF NOT EXISTS your_table_name ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT ) """ # Execute the table creation query cursor.execute(create_table_query) print("Table created successfully") except mysql.connector.Error as error: print("Error occurred while connecting to MySQL:", error) finally: if 'connection' in locals() and connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")
Make sure to replace 'your_username', 'your_password', and 'your_database_name' with your actual MySQL credentials and database name.
Replace 'your_table_name' with the name you want to give to your table.
This script connects to the MySQL server, creates a new table with specified columns (id, name, and age), and prints a success message if the operation is successful.
Remember to handle exceptions and close the connection properly.