1.4.4.3 Inserting Data

The insert method looks like this:

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

insert( table,columns,values,[autoExecute,])
table
A string containing the name of the table to select from or if selecting from multiple tables, a list or tuple of table names.
columns
A list or tuple of column names in that same as the values which are going to be inserted into those coulmns. Can be a string if only one column is going to have values inserted
values
A list or tuple of values to be inserted into the columns named by the columns variable. Can be the value rather than a list if there is only one value.
autoExecute
If False the function returns the SQL string to perform the desired operations. If True the SQL is executed and the results converted and returned in the appropriate form. If not specified takes the value specifed 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(
    'Person',
    ['LastName', 'FirstName', 'Address', 'DateOfBirth'],
    ['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 class.

The table now looks like this:

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

See About this document... for information on suggesting changes.