← Back to Python Course | Chapter 15: Python & MySQL | Lesson 3 of 12

Python MySQL Create Table

Tables किसी database के अंदर CREATE TABLE SQL statement इस्तेमाल करके बनाई जाती हैं, जिसे Python से ठीक उसी तरह चलाया जाता है जैसे कोई और SQL command चलाई जाती है -- table के columns और types describe करने वाली SQL string बनाएँ, फिर उसे cursor.execute() को पास कर दें।
Syntax
python
cursor.execute("CREATE TABLE table_name (column1 type, column2 type)")

Basic Table बनाना

cursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))") तीन columns वाला एक नया table define करता है: एक auto-incrementing integer primary key, और name व address के लिए दो text columns।

Note: किसी table को हमेशा एक PRIMARY KEY column दें -- यह हर बाद के update, delete, या targeted lookup को काफी सरल और तेज़ बना देता है।
Warning: Column definitions को commas से अलग करना और पूरी column list को parentheses में wrap करना ज़रूरी है -- कोई comma या parenthesis छूट जाना एक बहुत आम SQL syntax error है।

उदाहरण: Basic Table Creation

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute(
    "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, "  # auto-incrementing primary key
    "name VARCHAR(255), address VARCHAR(255))"
)
print("Table created")

Column Data Types चुनना

MySQL अलग-अलग तरह के data के लिए specific column types देता है -- पूरे numbers के लिए INT, n characters तक की variable-length text के लिए VARCHAR(n), लंबे text के लिए TEXT, dates के लिए DATE/DATETIME, और currency जैसे exact-precision numbers के लिए DECIMAL।

Note: Monetary values के लिए FLOAT नहीं, DECIMAL इस्तेमाल करें -- floating-point types छोटी rounding errors ला सकते हैं जो पैसों के मामले में मायने रखती हैं।
Warning: VARCHAR को एक maximum length argument चाहिए, जैसे VARCHAR(255) -- इसे छोड़ देना एक syntax error है, TEXT के विपरीत जिसे कोई length argument नहीं चाहिए।

उदाहरण: Choosing Column Data Types

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute(
    "CREATE TABLE orders (id INT, price DECIMAL(10,2), placed_on DATE)"  # DECIMAL for exact-precision currency values
)
print("DECIMAL used for money, not FLOAT")

जाँचना कि Table पहले से मौजूद है या नहीं

CREATE TABLE IF NOT EXISTS tableName (...) CREATE DATABASE IF NOT EXISTS का table-level equivalent है -- अगर उस नाम का table पहले से मौजूद है तो यह error raise करने की बजाय चुपचाप कुछ नहीं करता, जो repeatable setup scripts में उपयोगी है।

Note: किसी भी ऐसी setup script के लिए IF NOT EXISTS इस्तेमाल करें जो एक से ज़्यादा बार चल सकती है, जैसे किसी application की first-run initialization logic।
Warning: IF NOT EXISTS यह check नहीं करता कि EXISTING table की structure आपके बनाने की कोशिश से मेल खाती है या नहीं -- अगर उस नाम का table मौजूद है तो यह सिर्फ creation को पूरी तरह skip कर देता है।

उदाहरण: Checking If a Table Already Exists

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS customers (id INT PRIMARY KEY)")  # no error if the table already exists
print("Safe to run more than once")

Creation Confirm करने के लिए SHOW TABLES इस्तेमाल करना

cursor.execute("SHOW TABLES") और फिर cursor पर iterate करना currently selected database के हर table को list करता है, यह जल्दी confirm करने का एक तरीका है कि CREATE TABLE statement असल में सफल हुआ या नहीं।

Note: किसी भी table-creation logic के तुरंत बाद, development के दौरान SHOW TABLES चलाएँ, ताकि structural गलतियाँ बाद में data insert करते समय पकड़ने की बजाय तुरंत पकड़ी जाएँ।
Warning: SHOW TABLES सिर्फ table names list करता है, उनकी column structure नहीं -- उस स्तर की detail के लिए DESCRIBE tableName इस्तेमाल करें।

उदाहरण: Using SHOW TABLES to Confirm Creation

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute("SHOW TABLES")  # lists every table in the current database
cursor.__iter__.return_value = iter([("customers",), ("orders",)])
for table in cursor:
    print(table)

Foreign Keys और Table Relationships

एक FOREIGN KEY constraint एक table के किसी column को दूसरे table की primary key से जोड़ता है, referential integrity लागू करते हुए -- MySQL किसी ऐसे insert को reject कर देगा जो किसी non-existent parent row को reference करता है, जिससे related tables एक-दूसरे के साथ consistent रहती हैं।

Note: Tables बनाने से पहले अपने foreign key relationships (कौन सा table किसे reference करता है) design कर लें, क्योंकि referenced (parent) table को referencing (child) table बनने से पहले पहले से मौजूद होना चाहिए।
Warning: Foreign key column और referenced primary key column, दोनों को आमतौर पर matching, compatible data types चाहिए होते हैं, वरना CREATE TABLE statement fail हो जाएगा।

उदाहरण: Foreign Keys and Table Relationships

python
from unittest.mock import MagicMock

conn = MagicMock()
cursor = conn.cursor()
cursor.execute(
    "CREATE TABLE orders (id INT PRIMARY KEY, customer_id INT, "
    "FOREIGN KEY (customer_id) REFERENCES customers(id))"  # enforces that customer_id must reference a real customer
)
print("orders.customer_id must reference an existing customers.id")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.