1.4.13.2 Inserting Data

The insert method looks like this:

The insert() method of a web.database cursor looks like this:

insert( table, columns, values, __sqlValues, [execute])
Insert values into the columns in table. Either values or __sqlValues can be specified but not both.
table
The name of the table to insert into
columns
A sequence of column names in the same order as the values which are going to be inserted into those columns. Can be a string if only one column is going to have values inserted
values
A sequence of Python values to be inserted into the columns named in the columns variable. Can be the value rather than a list if there is only one value. If values is specified then __sqlValues must be either an empty sequence or contain a list of all quoted SQL strings for the columns specified in which case values contains the Python values of the SQL strings to be substituted for ? parameters in the __sqlValues sequence.
__sqlValues
A sequence of quoted SQL strings to be inserted into the columns named in the columns variable. Can be the value rather than a list if there is only one value. If __sqlValues is specified and contains ? parameters for substitution then values contains the values to be substituted. Otherwise values must be an empty sequence.
execute
If False the method returns the SQL string to perform the desired operations. If True the SQL is executed. If not specified takes the value specified in the cursor which by default is True

To insert data into a table using SQL you would use the following command:

INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)

For example consider the table used to demonstrate the select() method:

+----------+-----------+---------+-------------+
| LastName | FirstName | Address | DateOfBirth |
+----------+-----------+---------+-------------+

The SQL command to insert some information into the table might look like this:

INSERT INTO Person (LastName, FirstName, Address, Age)
VALUES ('Smith', 'John', '5 Friendly Place', '1980-01-01')

To insert the data using a web.database cursor we would do the following:

cursor.insert(
    table   = 'Person',
    columns = ['LastName', 'FirstName', 'Address', 'DateOfBirth'],
    values  = ['Smith', 'John', '5 Friendly Place', datetime.date(1980,1,1)],
)

Note: We specify the field values as real Python objects. The date was specified as a date object and was automatically converted. Python 2.2 users can also use import datetime if they have first used import web as the web modules come with a compatibility module.

The table now looks like this:

+----------+-----------+------------------+-------------+
| LastName | FirstName | Address          | DateOfBirth |
+----------+-----------+------------------+-------------+
| Smith    | John      | 5 Friendly Place | 1980-01-01  |
+----------+-----------+------------------+-------------+