What's causing my UPDATE statement not to work? - mysql

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!

Related

insert images into mysql database blob data type

i have picturebox and a label with path of picture location..
in mysql database i have field 'Photo' with 'Blob' Data Type
and iam using this code to insert data to database :
Try
MysqlCon = New MySqlConnection("Server=" & XIP & ";Database=" & XDB & ";User Id=" & XUser & ";Password=" & XPass & ";")
MysqlCon.Open()
MysqlCmd = New MySqlCommand("INSERT INTO staff(
Full_Name,
Full_Name_T,
Gender,
Num_ID,
Position,
Photo) VALUES
('" & txtfname.Text & "',
'" & txtfnamet.Text & "',
'" & cmbgender.Text & "',
'" & txtnumid.text & "',
'" & cmbposition.Text & "',
'" & lblphotopath.Text & "')", MysqlCon)
MysqlRdr = MysqlCmd.ExecuteReader
MysqlCon.Close()
Catch ex As Exception
Me.Enabled = True
MessageBox.Show(ex.Message & vbNewLine & "Try Again or Call Admin." & vbNewLine & "ERR.06")
Exit Sub
End Try
what iam trying to do is insert image to 'Photo' field using code above.
What should i add to my code above? or what should i change?

Identify a data entry without changing the ID

I am trying to create an update form. It is supposed to take values from the text boxes on the form and update that registry using the ID's autonumber as an identifier. It says I cannot edit the ID even though I don't think I am.
Private Sub edit_Click()
'Will edit the currently selected record
CurrentDb.Execute "UPDATE DataInput " & _
" SET ID=" & Me.txtID & _
", [Date]='" & Me.Date & "'" & _
", [Time Up]='" & Me.txttimeup & "'" & _
", [Notes]='" & Me.CboNotes & "'" & _
", [Time Down]='" & Me.txtTimeDown & "'" & _
" WHERE ID=" & Me.txtID.Tag
Me.txtID.Tag = ""
'refresh data on form
DataInput_subform.Form.Requery
'Disable Update Button
Me.edit.Enabled = False
'Enable Edit Button
Me.cmdEdit.Enabled = True
'Clear texts
cmdClear_Click
Try formatting your code in a more readable way and add a debug like
Dim sSql As String
sSql = "UPDATE DataInput SET [Date]=#" & Format(Me.Date,"mm/dd/yyyy") & "#, "
sSql = sSql & "[Time Up] = '" & Me.txttimeup & "', [Notes] ='" & Me.CboNotes & "', "
sSql = sSql & "[Time Down] = '" & Me.txtTimeDown & "' "
sSql = sSql & "WHERE ID = " & Me.txtID & " ;"
Debug.Print sSql
CurrentDb.Execute sSql

Set statement error

I am receiving the 3075 error (invalid operator) from the script below. The VBA error is marking the set statement in yellow. I don't understand why. What is lacking?
strSql = "SELECT FA_AVG.RadNr, (Left([Text],122)) AS LetaEfter1, Mid([Text],130,18) AS LetaEfter2, Right(Left([Text],184),36) AS LetaEfter3, FA_AVG.PerNr, FA_AVG.Fil, FA_AVG.GR1 " & _
"FROM FA_AVG " & _
"WHERE (((FA_AVG.RadNr)=20) AND ((Left([Text],122))='" & strTemp1 & "') AND ((Right(Left([Text],184),36))='" & strTemp3 & "') AND (Trim(FA_AVG.PerNr)='" & strPer & "'))"
Set rstAddData = CurrentDb.OpenRecordset(strSql)
Run this and study the output, and it will probably be quite clear to you why it won't run:
strSql = "SELECT FA_AVG.RadNr, (Left([Text],122)) AS LetaEfter1, Mid([Text],130,18) AS LetaEfter2, Right(Left([Text],184),36) AS LetaEfter3, FA_AVG.PerNr, FA_AVG.Fil, FA_AVG.GR1 " & _
"FROM FA_AVG " & _
"WHERE (((FA_AVG.RadNr)=20) AND ((Left([Text],122))='" & strTemp1 & "') AND ((Right(Left([Text],184),36))='" & strTemp3 & "') AND (Trim(FA_AVG.PerNr)='" & strPer & "'))"
Debug.Print strSQL

How to make text entry into table based on clicking an button in forms in Access 2010

I have created a form with submit buttons on it.
I have entered the data in the text box and then clicked on submit button.But the data is not getting saved in the table.Also,it is not showing any error message. It is not working at all.
Private Sub CmdAddNew_Click()
'add data to table
CurrentDb.Execute "INSERT INTO tblemployee(firstname,lastname,Address,city)" & _
" VALUES('" & Me.txtfirstname & "','" & Me.txtlastname & "','" & Me.txtaddress & "','" & Me.txtcity & "')"
try this:
Private Sub CmdAddNew_Click()
Dim dbs As DAO.Database, Sqltext As String, iCount As Integer
Set dbs = CurrentDb
Sqltext = "INSERT INTO tblemployee(firstname,lastname,Address,city) " & _
"VALUES('" & Me.txtfirstname & "','" & Me.txtlastname & _
"','" & Me.txtaddress & "','" & Me.txtcity & "');"
Debug.Print "SQL statement generated with variables:" & vbCrLf & Sqltext
dbs.Execute Sqltext, dbFailOnError
iCount = dbs.RecordsAffected
Debug.Print "..." & iCount & " row(s) inserted"
End Sub
The debug.print messages will print to the immediate window (Ctrl+g) to view from VBA editor, you can delete them if you want to once you have confirmed it's working.

Inserting string variable into sql string in vb.net

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.