ExecuteNonQuery() won't work for INSERT function - vb.net

First of all, I'm not a professional programmer. So there are some big faults possible in my program!
The problem is:
I linked my WPF file in visual express with a MS Access database (format 2003). Whenever I try to run the following (sorry for the dutch code):
Public Sub ToevoegenPersoon(voornaam As String, achternaam As String, mailadres As String, geboortedatum As Date, klantennummer As Integer, specialeCategorie As String)
Dim opdracht As OleDbCommand
Dim sqlOpdracht As String
sqlOpdracht = "INSERT INTO Klant (Voornaam, achternaam, mailadres, geboortedatum, klantennummer, specialeCategorie)" & _
"VALUES (" & Chr(34) & "" & voornaam & "" & Chr(34) & "," & Chr(34) & "" & achternaam & "" & Chr(34) & "," & Chr(34) & "" & _
mailadres & "" & Chr(34) & "," & Convert.ToString(geboortedatum) & "," & Convert.ToString(klantennummer) & "," & Chr(34) & "" & specialeCategorie & "" & Chr(34) & ")"
opdracht = New OleDbCommand(sqlOpdracht, connectie)
Debug.WriteLine(sqlOpdracht)
MsgBox(sqlOpdracht)
opdracht.Connection.Open()
opdracht.ExecuteNonQuery()
opdracht.Connection.Close()
End Sub
my program always has an error for the ExecuteNonQuery() function. This function is used for the following event:
Private Sub btnKlantToevoegen_Click(sender As Object, e As RoutedEventArgs) Handles btnKlantToevoegen.Click
Dim achternaam As String = boxVoornaam.Text
Dim voornaam As String = boxAchternaam.Text
Dim emailadres As String = boxEmailadres.Text
Dim geboortedatum As Date = GeboortedatumSelectie.SelectedDate
Dim klantennummer As Integer = 5
Dim specialeCategorie As String = "Jeugd"
Try
database.ToevoegenPersoon(voornaam, achternaam, emailadres, geboortedatum, klantennummer, specialeCategorie)
Catch ex As Exception
End Try
boxAchternaam.Clear()
boxVoornaam.Clear()
boxEmailadres.Clear()
End Sub
At the top, I stated the following to connect MS Access database with Visual express:
Private connectiestring As String = My.Settings.Database_Drijkoningen_Konings1ConnectionString
Private connectie As OleDbConnection
connectie = New OleDbConnection(connectiestring)
When running this program, the executenonquery() gives an error. And I have no clue whatsoever what it can be. Anybody who does?
Thanks in advance
Jeroen

Not sure if this could resolve your problem. I don't know the error message. However I will show a simple parameterized query that probably could help a lot
Public Sub ToevoegenPersoon(voornaam As String, achternaam As String, mailadres As String, geboortedatum As Date, klantennummer As Integer, specialeCategorie As String)
Dim opdracht As OleDbCommand
Dim sqlOpdracht As String
sqlOpdracht = "INSERT INTO Klant (Voornaam, achternaam, mailadres, " & _
"geboortedatum, klantennummer, specialeCategorie) " & _
"VALUES (?,?,?,?,?,?)"
opdracht = New OleDbCommand(sqlOpdracht, connectie)
opdracht.Parameters.AddWithValue("#p1", voornaam)
opdracht.Parameters.AddWithValue("#p2", achternaam)
opdracht.Parameters.AddWithValue("#p3", mailadres)
opdracht.Parameters.AddWithValue("#p4", Convert.ToString(geboortedatum))
opdracht.Parameters.AddWithValue("#p5", Convert.ToString(klantennummer))
opdracht.Parameters.AddWithValue("#p6", specialeCategorie)
opdracht.Connection.Open()
opdracht.ExecuteNonQuery()
opdracht.Connection.Close()
End Sub
Now, with a parameterized query there is no more concatenations on the command text and this alone will remove any possibility to forget some quote or comma between value. (Of course this removes also the Sql Injection problem and the parsing of strings that contain special characters)
There is still a problem to be resolved. The 4th and 5th parameter receive a string value. This requires the underlying field on the datatable to be a string field and not a DateTime. If this is not the case then you need to pass (as parameter value) just the date value

Related

INSERT INTO - errors, but allows input into table

For reasons I cannot see I get the following error message:
Compile error: Method or data member not found
when I use the following:
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Once I click OK and use the refresh button the entry is put into the database, but each time I do an entry I have to go to the same process.
I would like to figure out what method or data is missing?
I should add that there is an outnumber primary key field on this table (Berth_ID), and each time I use the cmd_Add button a new ID number is created for the new record. This includes creating a new ID number for the new record that triggers the error.
Here is all the VBA associated with this form
Private Sub Form_Load()
DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
Private Sub LOCATION_Change()
Me.txt_Cur_Flo = Me.LOCATION.Column(1)
Me.txt_Cur_Doc = Me.LOCATION.Column(2)
Me.txt_Cur_Ori = Me.LOCATION.Column(3)
End Sub
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Private Sub cmd_Clear_Click()
Me.Add_Boat = ""
Me.LOCATION = ""
Me.txt_Cur_Flo = ""
Me.txt_Cur_Doc = ""
Me.txt_Cur_Ori = ""
Me.Add_Boat.SetFocus
End Sub
Private Sub cmd_Close_Click()
DoCmd.Close
End Sub
Consider the best practice of parameterization and not string concatenation of SQL mixed with VBA variables. Due to missing quotes, the compiler attempts to reference a column name and not its literal value. Instead, consider parameterization with defined types which is supported with Access SQL using QueryDefs. Notice below, SQL and VBA are complete separate.
SQL (save as stored query)
PARAMETERS prmBoat TEXT, prmLoc INT, prmBerthed INT;
INSERT INTO BERTHAGE (BOAT, LOCATION, BERTHED)
VALUES(prmBoat, prmLoc, prmBerthed)
VBA
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("mySavedParamQuery")
' BIND PARAM VALUES
qdef!prmBoat = Me.Add_Boat
qdef!prmLoc = Me.LOCATION
qdef!prmBerthed = Me.In_Port
' EXECUTE ACTION QUERY
qdef.Execute
Set qdef = Nothing
Set db = Nothing
Even better, save your query with form controls intact and simply call OpenQuery:
SQL (save as stored query)
INSERT INTO BERTHAGE(BOAT, LOCATION, BERTHED)
VALUES(Forms!myForm!Add_Boat, Forms!myForm!LOCATION, Forms!myForm!In_Port)
VBA
Private Sub cmd_Add_Click()
Dim strSQL As String
DoCmd.SetWarnings False ' TURN OFF APPEND PROMPTS
DoCmd.OpenQuery "mySavedActionQuery"
DoCmd.SetWarnings True ' RESET WARNINGS
Call cmd_Clear_Click
End Sub
Missing opening parenthesis after VALUES. Also missing apostrophe in front of Me.Add_Boat. These special characters must always be in pairs, an even number by counting.
If Berth_Week and Berth_Year are number fields (and should be), don't use apostrophe delimiters.
If In_Port is a Yes/No field, don't use apostrophe delimiters.
The issue appears to be that I was doubling up the inputs into the 'week' and 'year' field. this was happening (I believe) because those text box fields were already accessing the week and year information directly from the default value on the BERTHAGE table. Essentially I went through each input and would run it individually waiting for the error to occur. Once it occurred I took it out of the INSERT INFO statement. With the removal of week and year, everything is working. That was a painful exercise, and still not complete, but I am back to a function form/DB so I'll take the small victories when they occur.
Private Sub cmd_Add_Click()
Dim strSQL As String
CurrentDb.Execute " INSERT INTO BERTHAGE " & "(BOAT, LOCATION, BERTHED) VALUES ('" & Me.Add_Boat & "'," _
& Me.New_Loc & "," _
& Me.In_Port & ");"
cmd_Clear_Click
DoCmd.Requery
End Sub`

SQL query works in access but not in excel

I need to get data from a recordset. The SQL query works fine in MS Access and returns exactly the expected values, but when the same query is lunched in VBA Excel, I get the following error:
No value given for one or more required parameters
Do you have any ideas why this problem occurs?
Thank you.
Philippe-Olivier Roussel
Private Sub CBtype_AfterUpdate()
Dim strConnexion As String
Dim connexion As New ADODB.Connection
strConnexion = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & Database & ""
connexion.Open strConnexion
Dim rsMarque As New ADODB.Recordset
Dim seltype As String
seltype = CBtype.Value
rsMarque.Open "SELECT DISTINCT tblMarque.marque_nom FROM tblMarque, tblModele WHERE " & _
" tblMarque.marque_id = tblModele.marque_id AND tblModele.marque_id IN " & _
" (SELECT DISTINCT tblModele.marque_id FROM tblModele, tblType " & _
" WHERE tblModele.type_id = tblType.type_id AND tblModele.type_id = " & _
" (SELECT tblType.type_id FROM tblType WHERE " & _
" (tblType.type_nom = " & seltype & ")))", connexion, adOpenStatic
rsMarque.MoveFirst
With UserForm2.CBmarque
.Clear
Do
.AddItem rsMarque!marque_nom
rsMarque.MoveNext
Loop Until rsMarque.EOF
End With
End Sub
This error message looks like an output from the DBMS rather than Excel
I think you might be missing the apostrophe before and after your string variable. See if
" (tblType.type_nom = '" & seltype & "')))" works (I'm assuming the column you're querying is varchar type, since you declared seltype as string)

SQL Result to Global Variable

Within my MDIParent Me_Load I have an SQL query that returns user information based upon Windows ID. This works well, however I'd really like to move this logic out into perhaps a module and assign each value in the db to a global variable to be used elsewhere. I'd like to be able to access the contact_id in any child form of the parent MDI. I'm used to PHP where I'd just assign it to a session variable that I could reference anywhere.
This is my current SQL Code
Dim sql_query As String
Dim errorMessages As New StringBuilder()
Dim cnn = ConfigurationManager.ConnectionStrings("sql_connection_string").ConnectionString
Dim adapter As SqlDataAdapter
Dim ds As New DataTable()
Dim User_ID As String
Dim User_First_Name As String
Dim User_Last_Name As String
Dim User_Contact_CD As String
Dim User_Login As String
sql_query = "SELECT Contact_ID, First_Name_CH, Last_Name_CH, Contact_CD, Login_VC FROM [Worktool].[dbo].[vwEmployees_T] WHERE Login_VC = '" & username & "'"
Using connection As New SqlConnection(cnn)
Try
If connection.State = ConnectionState.Closed Then connection.Open()
adapter = New SqlDataAdapter(sql_query, connection)
adapter.Fill(ds)
User_ID = ds.Rows(0)("Contact_ID").ToString()
User_First_Name = ds.Rows(0)("First_Name_CH").ToString()
User_Last_Name = ds.Rows(0)("Last_Name_CH").ToString()
User_Contact_CD = ds.Rows(0)("Contact_CD").ToString()
User_Login = ds.Rows(0)("Login_VC").ToString()
connection.Close()
Catch ex As SqlException
MsgBox("Sorry, there was an issue with the connection. Please try again ! ")
Dim i As Integer
For i = 0 To ex.Errors.Count - 1
errorMessages.Append("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
MsgBox(errorMessages.ToString())
End Try
End Using
'Assign messages
main_window_welcome.Text = "Welcome back, " & Replace(User_First_Name, " ", "") & " " & Replace(User_Last_Name, " ", "")
variable username is
Public username = Environ$("Username")
You've declared the 4 variables in the class and they are private to that class. At this point your code works. Hilight those 4 variable declarations and Cut them. Your code shows errors because you just removed the declarations.
Add a module to your solution (name it what you want)
paste the declarations into the module body.
change the Dim to Public.
Your errors disappear.
Your variables are now public and available throughout your solution.

VB.NET Update to Excel

I am developing an application in Visual Basic using Visual Studio 2013. In this application I am attempting to use an oledb UPDATE to write data out to an Excel spreadsheet treated as a database. I have tried numerous different formats of this but I either get a syntax error or it pretends to work but nothing actually gets written to the file. Can anyone tell me what is wrong with this code:
Public Function WriteToExcel(ExcelPath As String, dtUser As DataTable)
Dim vOffice As String = dtUser.Rows(0).Item("Office").ToString
Dim vDivision As String = dtUser.Rows(0).Item("Division").ToString
Dim vSection As String = dtUser.Rows(0).Item("Section").ToString
Dim vUser As String = dtUser.Rows(0).Item("UserID").ToString
Dim ExcelconnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ExcelPath & ";Extended Properties='Excel 12.0 Xml;HDR=YES';"
Dim BatchID As Long = 0
Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice WHERE [Primary User] = #uUser"
'Dim sql As String = "UPDATE [InstallationReport$] SET Office = #uOffice, " & _
'"Division = #uDivision, " & _
'"Section = #uSection " & _
'"WHERE [Primary User] = #uUser"
Using conn As New OleDb.OleDbConnection(ExcelconnString)
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#uOffice", vOffice)
cmd.Parameters.AddWithValue("#uDivision", vDivision)
cmd.Parameters.AddWithValue("#uSection", vSection)
cmd.Parameters.AddWithValue("#uUser", vUser)
Try
MessageBox.Show("Attempting to update " & vUser & ". " & vOffice & ", " & vDivision & ", " & vSection & "!")
conn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message & vbNewLine & ex.StackTrace)
End Try
End Using
End Function
Your SQL has two issues:
OleDbCommands use question marks ? as the placeholder for parameters, not #parameterName (that's for SqlCommands).
Section is a reserved keyword, so it needs to be escaped: [Section].

How to use Function VB.NET Insert To Database?

i using function with vb.net. i'm query sql to datagridview and insert data from datagridview to Databse By function.
But Error in function: The name 'EXHBK13004' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.
i want using function with insert to database.
Table Clother
Name Type
No (PK) int
Code nvarchar(12)
RClother int
CIDetail int
PO nvarchar(50)
Code (Button Save)
Private Sub btSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btSave.Click
For i As Integer = 0 To DgvItem.Rows.Count - 1
sendPDTStatus = FInsertClother(CStr(DgvItem.Rows(i).Cells(0).Value), CInt(DgvItem.Rows(i).Cells(1).Value), CInt(DgvItem.Rows(i).Cells(2).Value), _
DgvItem.Rows(i).Cells(3).Value)
Next
End Sub
Code Function
Public Function FInsertClother(ByVal Code As String, ByVal RClother As Integer, ByVal CIDetail As Integer, ByVal PO As String)
Dim Tr As SqlTransaction
Dim sqlCom As New SqlCommand
Dim sqlInsert As String
Dim ReturnValue As Integer
Tr = Conn.BeginTransaction
sqlCom.Connection = Conn
sqlInsert = "INSERT INTO Clother "
sqlInsert &= "(Code,RClother,CIDetail,PO) "
sqlInsert &= "VALUES(" & Code & "," & RClother & "," & CIDetail & "," & PO & ")"
sqlCom.Transaction = Tr
sqlCom.CommandText = sqlInsert
sqlCom.CommandType = CommandType.Text
ReturnValue = sqlCom.ExecuteScalar << Line Error
If ReturnValue = 0 Then
Tr.Commit()
Else
Tr.Rollback()
End If
Return ReturnValue
End Function
I try Debug this result
Name Value
sqlCom.CommandText "INSERT INTO Clother (Code,RClother,CIDetail,PO) VALUES(050030543003,5022,30543,EXHBK13004/3)"
sqlInsert "INSERT INTO Clother (Code,RClother,CIDetail,PO) VALUES(050030543003,5022,30543,EXHBK13004/3)"
Only field "PO" don't insert to database.
Thanks you for your time. :))
First of all I would remove the string concatenation and use a parameterized query to avoid parsing problems and Sql Injections (In your code you have passed two strings without using quotes and this will surely fail the insert because string fields require a quote delimiter)
Then I remove also the Transaction because, as it stands now the loop executes and confirms a single command for each row.
Also you seems to have a global connection object and this is a bad practice, you should open the connection and close it as soon as possible without keeping it open for the lifetime of your application.
Public Function FInsertClother(ByVal Code As String, ByVal RClother As Integer, ByVal CIDetail As Integer, ByVal PO As String)
Dim sqlInsert As String
Dim ReturnValue As Integer
sqlInsert = "INSERT INTO Clother " & _
"(Code,RClother,CIDetail,PO) " & _
"VALUES(#code, #clot, #id, #po)"
Using sqlCom = new SqlCommand(sqlInsert, conn)
sqlCom.Connection = Conn
sqlCom.Parameters.AddWithValue("#code",Code)
sqlCom.Parameters.AddWithValue("#clot", RClother)
sqlCom.Parameters.AddWithValue("#id",CIDetail)
sqlCom.Parameters.AddWithValue("#po",PO)
ReturnValue = sqlCom.ExecuteNonQuery
Return ReturnValue
End Using
End Function
A very useful enhancements would be to open the connection on the button click and pass it to this function. So when you have finished to loop over the rows you could close the connection via a Using Statement
You need to put the string values in quotes.
sqlInsert &= "VALUES('" & Code & "'," & RClother & "," & CIDetail & ",'" & PO & "')"
That said, you should not build a query string using concatenation. This makes your query subject to a SQL Injection attack. Instead, you should use a parametrized query. (as Steve shows in his answer).