Hi every one, i should say hi experts :D . Help me with this pretty code :)
The database:
"ID (Primary key)" | "Title"
0 | "title1"
1 | "title2"
2 | "title3"
3 | "title4"
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
The first procedure is a wrapper to add data to database fields (if the data doent exist) But update it the row with new data already exist.
Input:
Table = TableName
Columns = name of colomns that will be updated separated by comma (Ex1: "ID" , Ex2: "ID,Title,...")
Record() = string array that represent the new values( multiple values are separated with comma)
OK, before adding values to database, we should check if a row exists with this values :)
TO do this, creating a Stored Procedure is a best way to deal with the database fastly.
So... The problem now is, at the runtime, Miss OleDB throw this error:
Microsoft Jet database engine cannot find the input table or query 'IF' ....
Thanks in advance :D