我应该说嗨专家:D。用这个漂亮的代码帮我:)
数据库:
“ID(主键)” | “标题”
0 | "标题1"
1 | “标题2”
2 | "标题3"
3 | “标题4”
Sub AddRecord(ByVal Table As String, ByVal Columns As String, ByVal Record() As String)
Dim SubDir As String = ""
Dim Adapter As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM " & Table, connectionString)
Dim command As OleDbCommand
Dim tbCorrectSyntax = ""
Using connection As New OleDbConnection(connectionString)
Try
connection.Open()
Dim Commandtxt As String = ""
For i = 0 To Record.GetUpperBound(0)
If Record(i).IndexOf(",") > 0 Then
Dim tmpRec() As String = Nothing
Dim cols() As String = Nothing
tmpRec = Record(i).Split(",")
cols = Columns.Split(",")
For j = 0 To tmpRec.GetUpperBound(0)
tbCorrectSyntax &= cols(j) & " = '" & tmpRec(j) & "' " & IIf(j = tmpRec.GetUpperBound(0), "", " , ")
Next
End If
Dim txtCorrect As String = IIf(tbCorrectSyntax = "", Columns & " = " & Record(i), tbCorrectSyntax)
Commandtxt = "IF OBJECT_ID ( 'InsertOrUpdateItem', 'P' ) IS NOT NULL " & _
"DROP PROCEDURE InsertOrUpdateItem " & _
"GO " & _
"CREATE PROCEDURE InsertOrUpdateItem " & _
"AS " & _
"IF (EXISTS (SELECT * FROM " & Table & _
" WHERE " & txtCorrect & "))" & _
" begin " & _
"UPDATE (" & Table & ") " & _
txtCorrect & _
" WHERE " & txtCorrect & " " & _
" End " & _
" else " & _
" begin " & _
" INSERT INTO " & Table & " (" & Columns & ") " & _
" VALUES (" & Record(i) & ")" & _
" End " & _
"End "
'Commandtxt = "INSERT INTO " & Table & " (" & Columns & ") VALUES (" & Record(i) & ")"
command = New OleDbCommand(Commandtxt, connection)
command.CommandType = CommandType.StoredProcedure
command.ExecuteNonQuery()
Next
Catch ex As Exception
msgbox(ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
Function connectionString() As String
Return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DBdir & ";User Id=admin;Password=;"
End Function
第一个过程是一个包装器,用于将数据添加到数据库字段(如果数据不存在)但是用新数据更新它已经存在的行。
输入:
Table = TableName
Columns = 将要更新的列的名称,以逗号分隔(Ex1:“ID”,Ex2:“ID,Title,...”)
Record() = 表示新值的字符串数组(多个值用逗号分隔)
好的,在向数据库添加值之前,我们应该检查是否存在具有该值的行:)
为此,创建存储过程是快速处理数据库的最佳方法。
所以......现在的问题是,在运行时,Miss OleDB 抛出这个错误:
Microsoft Jet 数据库引擎找不到输入表或查询'IF'......。
提前致谢