Google News
logo
Python Program to Create a table
To create a table in a MySQL database 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 table in a MySQL database :

Example :
import mysql.connector

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

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

# Create a table
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")

# Print a message to indicate the table has been created
print("Table created successfully!")
In this 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, and `mydatabase` with the name of the database you want to create the table in.

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 table named `customers` using a SQL `CREATE TABLE` statement. The `id` column is defined as an `INT` data type with the `AUTO_INCREMENT` attribute and the `PRIMARY KEY` constraint. The `name` and `address` columns are defined as `VARCHAR` data types with a maximum length of 255 characters.

After the table has been created, the program prints a message to indicate that the table 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.