MySQL Create Table
A table definition should enforce the important rules of the records your script will store. Application validation does not replace database constraints.
Understand the idea
This lab table stores a required name and a non-negative stock count with an automatically assigned identifier. Run it in an empty designated lab, and inspect any existing definition instead of assuming IF NOT EXISTS would repair differences. Later examples use this exact schema and demonstrate their own read or write operation.
Where to try it
Use a local Python environment with mysql-connector-python and your own separate MySQL lab server. Read the lab setup below before running. This example is not connected to this website’s database and cannot run in the restricted online Python tool.
A worked example
import os
import mysql.connector
connection = mysql.connector.connect(
host=os.environ.get("DB_HOST", "127.0.0.1"),
user=os.environ["DB_USER"],
password=os.environ["DB_PASSWORD"],
database=os.environ["DB_NAME"],
)
cursor = connection.cursor()
try:
cursor.execute("CREATE TABLE workshop_products (product_id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(120) NOT NULL, stock INT NOT NULL CHECK (stock >= 0))")
connection.commit()
print("Created workshop_products")
except Exception:
connection.rollback()
raise
finally:
cursor.close()
connection.close()
Read the result
The table is ready for the insert lesson. It starts empty; no product appears merely because the schema exists.
Try one change
Inspect the table in your local database client and identify which rule protects each column.
Local lab setup
Use a local Python virtual environment with mysql-connector-python installed and a separate MySQL lab server. Run the create-database and create-table lessons first, then insert a few lab products. Set DB_HOST, DB_USER, DB_PASSWORD, and DB_NAME in the environment of the process that runs the script. These snippets are complete driver examples; they have not been run against your database.