+91 81900 98289

MySQL Insert

This MySQL Insert lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

INSERT adds one row. Pass values in the same order as the column list, or name the columns.

Never build the statement by gluing user text into the SQL. Use the driver parameters.

Example 1: Start here

The SQL shape is INSERT INTO learner (name, city) VALUES (%s, %s) with the values sent separately.

rows = [] # a list; the values stay in this order rows.append({"id": 1, "name": "Meera", "city": "Chennai"}) # add one item at the end of the list print(rows)

Example 2: Filter the rows

MySQL Insert is easier to see as a list of records. The filter keeps every row whose seats value is at least 10.

rows = [{"topic": "MySQL Insert", "seats": 31}, {"topic": "SQL", "seats": 12}] # a list; the values stay in this order print([row["topic"] for row in rows if row["seats"] >= 10]) # keep the items that pass the test

Example 3: Update one field

An update changes one field and leaves the rest of the record alone. On a database you would run an UPDATE or an update_one for the same change.

row = {"topic": "MySQL Insert", "seats": 31} # a dictionary; each key has one value row["seats"] = row["seats"] + 1 # change this one field print(row)

Example 4: Count the matches

Counting matches is the idea behind COUNT(*). Here the number 31 appears twice.

rows = [31, 4, 31] # a list; the values stay in this order print(sum(1 for value in rows if value == 31)) # keep the items that pass the test
The SQL shape is INSERT INTO learner (name, city) VALUES (%s, %s) with the values sent separately.
Call Now 81900 98289