Insert new records into database tables with automatic ID generation, type validation, and constraint handling.
The insert()
method adds new records to database tables. It automatically handles auto-increment primary keys, validates foreign key constraints, and prevents duplicate entries on unique fields across all supported databases.
insert(table_name: str, data: Dict[str, Any]) -> int
Type: str
Name of the table to insert data into. The table must exist before insertion.
Type: Dict[str, Any]
Dictionary mapping column names to their values. Must be a non-empty dictionary with valid column names and appropriate data types.
Type: int
The ID of the inserted record (from the database's lastrowid
or equivalent). For auto-increment primary keys, this will be the generated ID value.
Inserted user with ID: 1 Inserted second user with ID: 2
You can specify explicit ID values when needed:
Electronics category ID: 100 Books category ID: 200
Insert data with foreign key references:
Created author with ID: 1 Created posts with IDs: 2, 3
Insert multiple records efficiently:
Inserted Laptop with ID: 1 Inserted Mouse with ID: 2 Inserted Desk Chair with ID: 3 Inserted Monitor with ID: 4 All product IDs: [1, 2, 3, 4]
Returns cursor.lastrowid
for the inserted record:
Returns cursor.lastrowid
from MySQL's AUTO_INCREMENT:
Returns the SERIAL primary key value:
Returns the ObjectId as an integer representation:
First user created with ID: 1 Insertion failed: Duplicate entry on unique field: UNIQUE constraint failed: users.username This username already exists! Second user created with ID: 2 Foreign key error: Foreign key constraint failed: FOREIGN KEY constraint failed Referenced author does not exist!
Insert data using the Akron CLI with the seed
command:
Seeded data into users. Seeded data into posts. Seeded data into products.
After inserting data, you can retrieve and manipulate it: