|
楼主 |
发表于 2019-8-16 12:33
|
显示全部楼层
进阶, 使用commit
在操作数据库时,不想实时读写,遇到错误的时候需要回滚 引用这段代码时,需要自己根据实际情况修改SQL相关字段名称和语句
新增
- Sub Main_Insert()
-
- Dim objConn As ADODB.Connection
- Dim i As Integer, total_row As Integer
- Dim myPath As String
- '放在共享盘上,方便多人操作,权限需要通过共享盘来控制
- myPath = "\\ant\Database" & "\db.mdb"
-
- With Sheets("新增")
- total_row = .Cells(Rows.Count, 1).End(xlUp).Row
- 'Excel一大特征就是灵活,代价是对数据格式控制的不好,即便设置了数据有效性,也会被用户轻易覆盖,本段代码用来检查key值是否为空,可以增加检查其他字段
- i = 2
- Do While (i <= total_row)
- If .Cells(i, 1).Value = Null Or Trim(.Cells(i, 1).Value) = "" Then
- MsgBox ("第一列Tracking Number有空值,请检查后再上传! --" & i & "行")
- Exit Sub
- End If
- i = i + 1
- Loop
-
- Set objConn = Connect(myPath)
- On Error GoTo CleanFail
- objConn.BeginTrans
- i = 2
- Do While (i <= total_row)
- Tracking_Number = .Cells(i, 1).Value
- Depart_Date = .Cells(i, 2).Value
- Scan_Date = .Cells(i, 3).Value
- User_Name = .Cells(i, 4).Value
- Report_ID = .Cells(i, 5).Value
- Filling_Number = .Cells(i, 6).Value
- Uploader = .Cells(i, 7).Value
- strSQL = "Insert Into Expense (Tracking_Number,Depart_Date,Scan_Date,User_Name,Report_ID,Filling_Number,Uploader) " & _
- "Values('" & Tracking_Number & "'," & _
- IIf(Depart_Date = 0, "Null", "'" & Depart_Date & "'") & "," & _
- IIf(Scan_Date = 0, "Null", "'" & Scan_Date & "'") & ",'" & _
- User_Name & "','" & Report_ID & "','" & Filling_Number & "','" & Uploader & "')"
-
- Set cmd = New ADODB.Command
- Set cmd.ActiveConnection = objConn
- cmd.CommandType = adCmdText
- cmd.CommandText = strSQL
- cmd.Execute
- i = i + 1
- Loop
- '循环全部完成后统一提交
- objConn.CommitTrans
-
- End With
-
- CleanExit:
- Call CloseConnection(objConn)
- MsgBox "数据上传成功!", vbOKOnly, "成功"
- Exit Sub
-
- CleanFail:
- objConn.RollbackTrans
- MsgBox "上传数据有误,本次未成功上传." & Err.Description
- Debug.Print Err.Number, Err.Description
- Call CloseConnection(objConn)
- Exit Sub
- End Sub
复制代码 |
|