关于VB的添加
AddNew 方法范例
该范例使用 AddNew 方法创建具有指定名称的新记录。
Public Sub AddNewX()
Dim cnn1 As ADODB.Connection
Dim rstEmployees As ADODB.Recordset
Dim strCnn As String
Dim strID As String
Dim strFirstName As String
Dim strLastName As String
Dim booRecordAdded As Boolean
' 打开连接。
Set cnn1 = New ADODB.Connection
strCnn = "Provider=sqloledb;" & _
"Data Source=srv;Initial Catalog=pubs;User Id=sa;Password=;"
cnn1.Open strCnn
' 打开 Employee 表。
Set rstEmployees = New ADODB.Recordset
rstEmployees.CursorType = adOpenKeyset
rstEmployees.LockType = adLockOptimistic
rstEmployees.Open "employee", cnn1, , , adCmdTable
' 从用户获取数据,雇员 ID 的格式应为:
' 名、中间名和姓的三个首字母,
' 五位数字,以及性别标识 M 或 F。
' 例如,Bill Sornsin 的雇员 ID 为:B-S55555M。
strID = Trim(InputBox("Enter employee ID:"))
strFirstName = Trim(InputBox("Enter first name:"))
strLastName = Trim(InputBox("Enter last name:"))
' 只在用户输入姓和名之后进行。
If (strID <> "") And (strFirstName <> "") _
And (strLastName <> "") Then
rstEmployees.AddNew
rstEmployees!emp_id = strID
rstEmployees!fname = strFirstName
rstEmployees!lname = strLastName
rstEmployees.Update
booRecordAdded = True
' 显示新添加的数据。
MsgBox "New record: " & rstEmployees!emp_id & " " & _
rstEmployees!fname & " " & rstEmployees!lname
Else
MsgBox "Please enter an employee ID, " & _
"first name, and last name."
End If
' 删除新记录,因为这只是演示。
cnn1.Execute "DELETE FROM employee WHERE emp_id = '" & strID & "'"
rstEmployees.Close
cnn1.Close
End Sub