Inserting string variable into sql string in vb.net - sql-server-2008

I am having a hard time inserting WONum into my sql string.
I have tried using ' and double '' around WONum. Someone also suggested # and [] around it, but nothing is working thus far.
I keep getting the following error: Incorrect syntax near '1577'
WONum value is actually WO-1577 during run time, but when DA.fill is executed I get that error. I starting to think that the dash is doing something in sql that I'm not aware of. Any help would help, because I have to do several more similar functions in my application.
Public Function GetTechTimes(ByVal WONum As String)
Dim strSQL As String = "Select customer_name, workorder_work_to_be_performed, workorder_work_performed, workorder_notes, workorder_warranty_work, workorder_open_date, workorder_status,workorder_completion_date, wo_tech_name, wo_tech_time, wo_parts_description from Customers, workorders, WorkOrder_Technicians, WorkOrder_Parts Where(customer_id = workorder_customer And wo_tech_wo_id = workorder_id And wo_parts_wo_id = workorder_id And workorder_number = " & WONum & ""
Dim DA As New SqlDataAdapter(strSQL, Conn)
Dim DS As New DataSet
DA.Fill(DS, "TechTimes")
Return DS
End Function

Use Sql-Parameters! That will avoid conversion or other issues and - more important - prevents SQL-Injection attacks.
Public Function GetTechTimes(ByVal WONum As String) As DataSet
Dim strSQL As String = "SELECT customer_name, " & Environment.NewLine & _
"workorder_work_to_be_performed," & Environment.NewLine & _
"workorder_work_performed, " & Environment.NewLine & _
"workorder_notes, " & Environment.NewLine & _
"workorder_warranty_work, " & Environment.NewLine & _
"workorder_open_date, " & Environment.NewLine & _
"workorder_status, " & Environment.NewLine & _
"workorder_completion_date," & Environment.NewLine & _
"wo_tech_name, " & Environment.NewLine & _
"wo_tech_time, " & Environment.NewLine & _
"wo_parts_description" & Environment.NewLine & _
"FROM(customers," & Environment.NewLine & _
" workorders," & Environment.NewLine & _
" workorder_technicians," & Environment.NewLine & _
" workorder_parts)" & Environment.NewLine & _
"WHERE customer_id = workorder_customer " & Environment.NewLine & _
"AND wo_tech_wo_id = workorder_id " & Environment.NewLine & _
"AND wo_parts_wo_id = workorder_id " & Environment.NewLine & _
"AND workorder_number = #workorder_number "
Using con = New SqlConnection(YourConnectionString)
Using da = New SqlDataAdapter(strSQL, con)
da.SelectCommand.Parameters.AddWithValue("#workorder_number", WONum)
Dim DS As New DataSet
da.Fill(DS)
Return DS
End Using
End Using
End Function
Note that i've also used Using-statements to ensure that all gets diposed even in case of an exception.
Bye the way, the reason for your exception: you had an opening brace here: Where(customer_id which was never closed.

As long as workorder_number is a string then putting single quote ' around the WONum is all you need.
You won't need # or square brackets.
If it's not working with the single quote then ensure you've identified/isolated your problem correctly. Remove the And workorder_number = " & WONum & "" from the end of your sql and see if it works without that. If not, then your problem isn't in the WONum, it's earlier in the string.

Related

Update listbox ROWSOURCE when making a selection from a drop down

I have scoured around for topics relating to the idea of changing a listbox recordsource using VBA and I have created my own piece.. but it only works 1/2 way.
I have a form for tracking attendance issues for associates.. We have 2 locations, 1 in Az and 1 in Tx.. Due to recent laws that changed in Az our policies were updated.. The difference is in Az an occurrence is held for 1 year (or 365 days) and in Tx the occurrence is held for 3 months (90 days).
The basic idea is this:
If the text box for "supervisor state" = Az, the HISTORYBOX should show/calculate out 365 days of records.. else if the "supervisor state" = Tx then the HISTORYBOX should show/calculate 90 days of records.
My issue is when selecting an AZ supervisor.. it is still pulling the 90 day version of the code.. not the 365 day version.
Here is the code I have been able to create so far:
Public Sub ChangeHistory()
Dim strSQL As String
If Me.txtsupervisorstate.Value = "AZ" Then
strSQL = "SELECT OccuTable.ValueOfOccurance, " & _
" OccuTable.Short_Code_Occurance, " & _
" OccuTable.OccuranceDate, " & _
" OccuTable.Roll_Off_Date, " & _
" OccuTable.Notes, " & _
" OccuTable.AssociatedIDNumber " & _
" FROM OccuTable GROUP BY OccuTable.ValueOfOccurance, " & _
" OccuTable.Short_Code_Occurance, " & _
" OccuTable.OccuranceDate, " & _
" OccuTable.Roll_Off_Date, " & _
" OccuTable.Notes, " & _
" OccuTable.AssociatedIDNumber " & _
" WHERE (((OccuTable.OccuranceDate) Between
Date() And Date()-365) And " & _
"
((OccuTable.AssociatedIDNumber)=Forms!OccuranceTracker!txtAssociateID))
ORDER BY OccuTable.OccuranceDate DESC;"
ElseIf Me.txtsupervisorstate.Value = "TX" Then
strSQL = " SELECT OccuTable.ValueOfOccurance, " & _
" OccuTable.Short_Code_Occurance, " & _
" OccuTable.OccuranceDate, " & _
" OccuTable.Roll_Off_Date, " & _
" OccuTable.Notes, " & _
" OccuTable.AssociatedIDNumber " & _
" FROM OccuTable GROUP BY OccuTable.ValueOfOccurance, " & _
" OccuTable.Short_Code_Occurance, " & _
" OccuTable.OccuranceDate, " & _
" OccuTable.Roll_Off_Date, " & _
" OccuTable.Notes, " & _
" OccuTable.AssociatedIDNumber " & _
" WHERE (((OccuTable.OccuranceDate) Between
Date() And Date()-90) And
((OccuTable.AssociatedIDNumber)=Forms!OccuranceTracker!txtAssociateID))
ORDER BY OccuTable.OccuranceDate DESC;"
Me.listBoxPastOccurances.RowSource = strSQL
End If
Call SumOfOccu
End Sub
Here is what the form looks like:
AttendanceForm
Oh my goodness I was WAYYY overthinking this issue. My newish self to VBA was trying to find the most convoluted and confusing way to make this work.. After ALOT of research around StackOverflow I found that I can write a query and save that query for future use.. So I wrote 2 individual queries (Occurrences365 and Occurrences90).. These duplicated the original query for the listbox (when I only needed the 90 day version), which was known to work; which made creating the 365 day version super simple.
Then I was able to reduce all my other convoluted code down to this:
Public Sub ClearHistory()
If Me![txtsupervisorstate] = "AZ" Then
Me![listBoxPastOccurances].RowSource = "Occurrences365"
ElseIf Me![txtsupervisorstate] = "TX" Then
Me![listBoxPastOccurances].RowSource = "Occurrences90"
End If
Call SumOfOccu
End Sub
Public Function SumOfOccu()
If Me![txtsupervisorstate] = "AZ" Then
Me.txtSumOfOccu = DSum("valueofoccurance", "occurrences365")
ElseIf Me![txtsupervisorstate] = "TX" Then
Me.txtSumOfOccu = DSum("valueofoccurance", "occurrences90")
End If
End Function
Now I can go back and start eliminating unnecessary subs/functions, clean up the naming conventions and make it overall 'cleaner'.
For anyone interested.. the queries look like this after I wrote them as a saved query.
SELECT OccuTable.ValueOfOccurance, OccuTable.ShortCodeOccurance,
OccuTable.OccuranceDate, OccuTable.RollOffDate, OccuTable.Notes,
OccuTable.AssociatedIDNumber
FROM OccuTable
GROUP BY OccuTable.ValueOfOccurance, OccuTable.ShortCodeOccurance,
OccuTable.OccuranceDate, OccuTable.RollOffDate, OccuTable.Notes,
OccuTable.AssociatedIDNumber
HAVING (((OccuTable.OccuranceDate) Between Date() And Date()-365) AND
((OccuTable.AssociatedIDNumber)=[Forms]![OccuranceTracker]![txtAssociateID]))
ORDER BY OccuTable.OccuranceDate DESC;
again.. the only difference between the 2 is this one piece.
And Date()-365)
And Date()-90)
But everything works!
Thank you so much for the suggestions and pushing me to keep looking!

Error on INSERT INTO statement

I have the following and getting the error in INSERT INTO statement. I've done a debug.print and pasted back into SSMS and it works just fine so I'm really stumped. The syntax looks fine to me but I know sometimes going from straight SQL to VBA SQL can be tricky. I had a feeling it was the EXISTS section and I took that out and made the appropriate edits and still got the error msg. Any suggetions?
sqlstr = "INSERT INTO [database.[dbo].[table]" & _
"(" & _
"User_name" & _
",Client_Id" & _
",Client_Name" & _
",UserAccess" & _
",UserId" & _
")" & _
"SELECT " & _
"User_name = '" & UserName & "'" & _
",Client_Id = " & Me.ClientList.ItemData(ClientID) & "" & _
",Client_Name = '" & Me.ClientList.Column(1, ClientID) & "'" & _
",UserAccess = 0" & _
",UserId = " & UserId & "" & _
" WHERE NOT EXISTS (SELECT 1 FROM [database].[dbo].[table] where UserID = " & UserId & " and Client_Id = " & Me.ClientList.ItemData(ClientID) & ")"
Access SQL != T-SQL.
You either need to run this SQL string as a Pass-Through query, then it's the same as running it in SSMS.
Or translate it into Access SQL.
At the very most you must change the table names into the names of the linked tables in Access (which certainly aren't [database].[dbo].[table])
If you need more help with option 2, please post the formatted result of Debug.Print sqlstr

3011 error code access recordset vba

This is the code that I have worked over many many times, fix one error code3061, then another, now this. ANY IDEAS WHY THIS ERROR IS HAPPENING, all objects spelled correctly?
Dim strSQL As String
Dim strForms As String
strForms = [Forms]![frmEnterResRecordset]![txtPhone]
MsgBox strForms
strSQL = "SELECT tblCustomer.IDCustomer, tblCustomer.PHONE, tblCustomer.LASTNAME, " & _
"tblCustomer.FIRSTNAME, tblCustomer.NAME, tblCustomer.EMAIL " & _
"FROM tblCustomer " & _
"WHERE (((tblCustomer.PHONE) Like " & "*'" & strForms & "'*" & "));"
Check your syntax near the Like operator. The asterisks are outside the single quotes. Try replacing it as follows:
strSQL = "SELECT tblCustomer.IDCustomer, tblCustomer.PHONE, tblCustomer.LASTNAME, " & _
"tblCustomer.FIRSTNAME, tblCustomer.NAME, tblCustomer.EMAIL " & _
"FROM tblCustomer " & _
"WHERE (((tblCustomer.PHONE) Like " & "'*" & strForms & "*'" & "));"
Something I like to do when building dynamic SQL statements like this is to print it to the debug window with the following statement:
debug.print strSQL
It's easier to spot statements like:
Like *'my_entered_value'*

VB.net update query is not giving errors and not updating my sql database

Dim conntps As MySqlConnection
Dim myconnstringtps As String
conntps = New MySqlConnection()
Dim mycommand As New MySqlCommand
Dim Updatepayments As String = "update payments set payments.payorname='" & _
epayorname.Text & "', payments.cardnumber='" & eccnumber.Text & _
"', payments.bankname='" & ebankname.Text & "', payments.checkaccountnumber='" & _
eaccountnumber.Text & "', payments.checkroutingnumber='" & _
erouting.Text & "', payments.cardexpirationdate='" & eexpmonth.Text & "/" & _
eexpireyear.Text & "', payments.cardexpirationmonth='" & _
eexpmonth.Text & "', payments.cardexpirationyear='" & eexpireyear.Text & _
"', payments.cardaddress='" & eaddy.Text & "', payments.cardzipcode='" & _
ezip.Text & "', payments.threedigitnumber='" & ecvv.Text & _
"' where payments.filenumber='" & TextBox1.Text & "' and paymentstatus='PENDING';"
myconnstringtps = "server=localhost; user id=root; " & _
"password=1C0cac0la; database=collectionsmax"
Try
conntps.Open()
Try
mycommand.Connection = conntps
mycommand.CommandText = Updatepayments
mycommand.ExecuteNonQuery()
conntps.Close()
mycommand.Dispose()
Catch myerror As MySqlException
MsgBox("error connecting:" & myerror.Message)
End Try
Catch myerror As MySqlException
MsgBox("error connecting:" & myerror.Message)
Finally
If conntps.State <> ConnectionState.Closed Then conntps.Close()
MsgBox("Successfully Changed")
End Try
I am not getting any errors or exceptions when attempting to run the code.
I have tried to output the generated update query to a text box and running the code though mysql management studio, and it works perfectly. so im pretty sure its not an issue with the actual query being sent to the server.
I have used almost this exact same code to do insert into statements with no issues.
It is not updating the database when the code is ran through my VB.net application using the above outlined code.
You don't set the connection string in the MySqlConnection
myconnstringtps = "server=localhost; user id=root; password=1C0cac0la;......"
conntps = New MySqlConnection(myconnstringtps)
apart from that, you need to use parametrized query to avoid problems with single quotes inside your strings and the Sql Injection Attack security problem
Dim Updatepayments As String = "update payments " & _
"set payments.payorname=#name," & _
"payments.cardnumber=#cnum," & _
"payments.bankname=#bank," & _
"payments.checkaccountnumber=#actnum," & _
"payments.checkroutingnumber=#routing," & _
"payments.cardexpirationdate=#monthyear," & _
"payments.cardexpirationmonth=#month," & _
"payments.cardexpirationyear=#year," & _
"payments.cardaddress=#address," & _
"payments.cardzipcode=#zip," & _
"payments.threedigitnumber=#digits " & _
"where payments.filenumber=#file and paymentstatus='PENDING'"
Dim mycommand As New MySqlCommand(Updatepayments, conntps)
mycommand.Parameters.AddWithValue("#name", epayorname.Text)
mycommand.Parameters.AddWithValue("#cnum", eccnumber.Text)
mycommand.Parameters.AddWithValue("#bank", ebankname.Text)
mycommand.Parameters.AddWithValue("#actnum", eaccountnumber.Text);
mycommand.Parameters.AddWithValue("#routing", erouting.Text)
mycommand.Parameters.AddWithValue("#monthyear", eexpmonth.Text & "/" & eexpireyear.Text)
mycommand.Parameters.AddWithValue("#month", eexpmonth.Text)
mycommand.Parameters.AddWithValue("#year", eexpireyear.Text)
mycommand.Parameters.AddWithValue("#address", eaddy.Text)
mycommand.Parameters.AddWithValue("#zip", ezip.Text)
mycommand.Parameters.AddWithValue("#digits", ecvv.Text)
mycommand.Parameters.AddWithValue("#file", TextBox1.Text)
Other problematic point: Are you sure that your fields are all of string type? You pass for every field a string and surround the value with single quotes. This could fail if someone of your fields are not of string type. (these fields in particular could be not of string type payments.cardnumber, payments.checkaccountnumber, payments.cardexpirationmonth,payments.cardexpirationyear,payments.threedigitnumber)
Use command parameters. This makes it both safer (SQL injection) and easier to handle.
Dim Updatepayments As String = "UPDATE payments SET payments.payorname=#1, " & _
"payments.cardnumber=#2, ..." & _
"WHERE payments.filenumber=#11 AND paymentstatus='PENDING';"
mycommand.Parameters.AddWithValue("#1", epayorname.Text);
mycommand.Parameters.AddWithValue("#2", eccnumber.Text);
...
You can also use parameter names like #epayorname with SQL-Server but some connection types (like ODBC) only allow positional parameters.
Red alert You are obviously dealing with credit card information here and yet you are leaving yourself and your customers vulnerable to SQL injection attacks!
Also you have a password in your code that you posted on the public Internet!
(And Steve seems to have the right answer.)

What's causing my UPDATE statement not to work?

Good evening all,
I'm using the following as an attempt to update records in my MySQL database, but the records aren't being updated and I'm not catching any exceptions either. Your help would be kindly appreciated:
dbConn = New MySqlConnection("Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=trojan;Password=horse;Database=accounting")
Try
If dbConn.State = ConnectionState.Open Then
dbConn.Close()
Else
Try
dbConn.Open()
Dim dbAdapter As New MySqlDataAdapter("UPDATE customer " & _
"SET accountNumber= '" & TextBoxAccount.Text & "', nameLAST='" & TextBoxLastName.Text & "', nameFIRST='" & TextBoxFirstName.Text & "'" & _
"nameSALUTATION='" & ComboBoxSalutation.SelectedItem & "', nameCOMPANY='" & TextBoxCompanyName.Text & "', addressSTREET='" & TextBoxAddress1.Text & "'" & _
"addressSTREET1='" & TextBoxAddress2.Text & "', addressCITY='" & TextBoxCity.Text & "', addressSTATE='" & ComboBoxState.SelectedItem & "'" & _
"addressZIPCODE='" & MaskedTextBoxZip.Text & "', phone='" & MaskedTextBoxPhone.Text & "', fax='" & MaskedTextBoxFax.Text & "', email='" & TextBoxEmail.Text & "'" & _
"WHERE accountNumber='" & TextBoxAccount.Text & "';", dbConn)
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
MessageBox.Show("Customer account SUCCESSFULLY updated!")
Call lockForm()
End If
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
Call lockForm()
dbConn.Close()
Use MySQLCommand instead of MySQLDataAdapter. You are defeating the purpose of using ADONet because still your code is vulnerable with sql injection. Make it parameterized. Below is a modified code from your code. It uses Using-End Using for proper handling of object disposal.
Dim ConnectionString As String ="Server=" & FormLogin.ComboBoxServerIP.SelectedItem & ";Port=3306;Uid=trojan;Password=horse;Database=accounting"
Dim iQuery As String = "UPDATE customer " & _
"SET accountNumber = #accountNumber, nameLAST = #nameLAST, nameFIRST = #nameFIRST, " & _
" nameSALUTATION = #nameSALUTATION, nameCOMPANY = #nameCOMPANY, addressSTREET = #addressSTREET, " & _
" addressSTREET1 = #addressSTREET1, addressCITY = #addressCITY, addressSTATE = #addressSTATE, " & _
" addressZIPCODE = #addressZIPCODE, phone = #phone, fax = #fax, email = #email " & _
"WHERE accountNumber = #accountNumber"
Using dbConn As New MySqlConnection(ConnectionString)
Using dbComm As New MySQLCommand()
With dbComm
.Connection = dbConn
.CommandType = CommandType.Text
.CommandText = iQuery
.Parameters.AddWithValue("#accountNumber", TextBoxAccount.Text )
.Parameters.AddWithValue("#nameLAST", TextBoxLastName.Text)
.Parameters.AddWithValue("#nameFIRST", TextBoxFirstName.Text)
.Parameters.AddWithValue("#nameSALUTATION", ComboBoxSalutation.SelectedItem)
.Parameters.AddWithValue("#nameCOMPANY", TextBoxCompanyName.Text)
.Parameters.AddWithValue("#addressSTREET", TextBoxAddress1.Text)
.Parameters.AddWithValue("#addressSTREET1", TextBoxAddress2.Text)
.Parameters.AddWithValue("#addressCITY", TextBoxCity.Text)
.Parameters.AddWithValue("#addressSTATE", ComboBoxState.SelectedItem)
.Parameters.AddWithValue("#addressZIPCODE", MaskedTextBoxZip.Text)
.Parameters.AddWithValue("#phone", MaskedTextBoxPhone.Text)
.Parameters.AddWithValue("#fax", MaskedTextBoxFax.Text)
.Parameters.AddWithValue("#email", TextBoxEmail.Text)
End With
Try
dbConn.Open
dbComm.ExecuteNonQuery()
MessageBox.Show("Customer account SUCCESSFULLY updated!")
Call lockForm()
Catch( ex as MySQLException)
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
Finally
dbConn.Close()
End Try
End Using
End Using
In this case, I would use ExecuteNonQuery as you can't use a MySQLDataAdapter the way you are trying to use it. Also please use paramters as what you are doing opens you up to SQL injection attacks. And finally you don't need to update accountNumber because you are using that to find the row which you want to update!