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()​