Inserting Data

Use insert() to add a new row to a table. Pass the table name and a dictionary where keys are column names and values are the data to insert. The statement is committed for you.

db.insert(table, data)

Parameters

Parameter Type Description
table str Name of the table
data dict Column-value pairs to insert. Required — there is no default.

Example

from easymysql.mysql import mysql

db = mysql('localhost', 'root', 'secret', 'shop')

db.insert('products', {
    'name': 'Laptop',
    'price': 999.99,
    'stock': 50,
})

This executes:

INSERT INTO products (name,price,stock) VALUES ('Laptop','999.99','50');
Every value is sent as a quoted string

Values are converted with str() and wrapped in single quotes, so the number 999.99 is written as '999.99'. MySQL coerces these literals back into numeric columns, so ordinary inserts behave as expected. It matters in two places: a Python None becomes the string 'None' rather than NULL, and True/False become 'True'/'False' rather than 1/0. Pass 0 and 1 for boolean columns, and use raw SQL when you need a real NULL.

Return value

insert() returns the cursor's lastrowid — the auto-increment ID assigned by MySQL to the row just inserted.

new_id = db.insert('products', {'name': 'Mouse', 'price': 29.99, 'stock': 200})
print(f"Inserted product with ID: {new_id}")

On a table with no AUTO_INCREMENT column this is 0. The same value is available afterwards from getLastId().

Commits

insert() calls commit() on every call, so each row is its own transaction. There is no batch-insert helper and no way to group several inserts into one transaction through this API — for that, drop down to execute().

Values are not escaped

The SQL string is built by concatenation, with no escaping and no placeholders. A value containing an apostrophe — "O'Brien" — produces a syntax error, and any value taken from user input is a SQL injection vector. Never pass unvalidated input. See Limitations.

Errors are printed, not raised

If the statement fails — unknown column, duplicate key, bad syntax — the exception is caught internally and printed to stdout as Exeception occured:…. Your code keeps running, and insert() still returns a lastrowid (the one left over from the previous statement). Check count() or re-query if you need certainty that a row landed.

Next step

Query your data →