Google News
logo
Python Program to Create primary key when creating a table
To create a table with a primary key in a MySQL database using Python, you can include the `PRIMARY KEY` constraint in the `CREATE TABLE` statement.

Here's an example Python program that creates a table with a primary key :

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 with a primary key
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")

# Check if the table was created
mycursor.execute("SHOW TABLES")
tables = mycursor.fetchall()

table_name = "customers"
if (table_name,) in tables:
  print("The table was created.")
else:
  print("The table was not created.")

# Close the connection
mydb.close()​
In this example, the `mysql.connector` module is imported and a connection is created to the MySQL server, just like in the previous examples.

Next, a cursor object is created using the `cursor()` method of the connection object.

To create a table with a primary key, the program executes the `CREATE TABLE` statement using the `execute()` method of the cursor object.

The statement specifies three columns: `id`, `name`, and `address`. The `id` column is defined with the `INT` data type and the `AUTO_INCREMENT` attribute, which generates a unique value for each new row added to the table.

The `PRIMARY KEY` constraint is added to the `id` column to make it the primary key for the table.

The program then checks if the table was created by executing the `SHOW TABLES` statement and checking if the table name is in the list of tables returned by the query.

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.