Insert | data | There are two ways in which a database inserts data from a form into a database.
1. Direct use of SQL statements
Advantages: Fast, not cost source
Disadvantage: Cannot pass too long field content, the field comparison is not easy to row wrong.
It is preferred to recommend experienced programmers.
Specific actions:
Suppose the form has the following fields: Username,password,sex,age
Corresponds to a value in the program that Username,password,sex,age has taken to a field by Request.Form or request.querystring.
There are username,password,sex,age fields in the database table user. Other age numeric field.
The connection object has been established and the link is open.
sql= "INSERT into [user] (Username,password,sex,age) value (' &username&" ', ' "&password&" ', ' "&sex & "'," &age& ")"
Conn.execute (SQL)
It is noteworthy that if the username contains "'" single quotes, an error occurs, and the workaround is to handle the string function first. My common approach is to create a sqlencode function.
function Sqlencode (str)
Sqlencode= "'" &replace (str, "", "") & ""
End Function
The SQL name above can be simplified to sql= "INSERT into [user] (Username,password,sex,age) VALUES (" &sqlencode (username) & "," & Sqlencode (password) & ", &sqlencode (Sex) &", "&age&") "
Multiple fields note the order of the values after the field names and values in the preceding list to note the one by one correspondence, and if the value is empty, you can leave it blank, but the delimited "," number cannot be omitted.
When you add a field that is a string field, pay attention to the "" "sign before and after the content.
In addition, the upper bracket is above the table name user because the user table may be a system table, and the upper bracket will not conflict with the system. Adding square brackets to the table name is also a good habit of ensuring code compatibility.
2. Using a Recordset object
Advantages: Code easy to read, error-removing
Disadvantage: Consuming system resources
Recommend novice use
The environment IBID. code is as follows:
Set RS=SERVER.CREATEOBEJCT ("ADODB. Recordset ")
Sql= "SELECT * from [user]
Rs.Open sql,conn,2,3
Rs.addnew ' Note that this behavior adds a new record, and if it misses, it changes the previous record.
RS ("username") =username
RS ("password") =password
RS ("Sex") =sex
RS ("age") =age
Rs.update ' writes updates to the database
Rs.close ' The fastest way to close a Recordset object is a good habit
Set rs=nothing ' releasing objects that are not used is also a good habit