-1

Can you please help me, what the problem of my code:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    'UPDATE Data
    openCon()


    Try
        cmd.Connection = con
        cmd.CommandText = "UPDATE emp_table SET FNAME = '" & TextBox1.Text & "', LNAME= '" & TextBox2.Text & "', AGE = '" & TextBox3.Text & "', GENDER ='" & Gender & "', OFFICE STAFF= '" & ComboBox1.Text & "' Where ID ='" & TxtID.Text & "' "
        cmd.ExecuteNonQuery()
        con.Close()
        MsgBox("Suceessfully Updated Record")
        TxtID.Clear()
        TextBox1.Clear()
        TextBox2.Clear()
        TextBox3.Clear()
        RBMale.Checked = False
        RBFemale.Checked = False
        ComboBox1.Text = ""

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try

End Sub
Steve
  • 213,761
  • 22
  • 232
  • 286
Hinata
  • 1
  • 1
  • 1
    So you have a problem here? And what is this problem? (Of course I assume you don't know anything about the dangers of string concatenation when building sql queries) – Steve Sep 19 '22 at 09:10
  • 1) You should create the connection, use it, then dispose of it, in the fashion shown in [SqlConnection Class](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection) (you may need to select VB.NET instead of C# near the top-right of the page). 2) You should use SQL parameters to pass the values, not concatenate them into the query string, as shown in [Parameterized Query for MySQL with C#](https://stackoverflow.com/a/652999/1115360) (it's pretty much the same for VB.NET). – Andrew Morton Sep 19 '22 at 09:17
  • 3
    Please provide a FULL and CLEAR explanation of the problem. You tell us what the problem is and we tell you what the solution is. It's not for us to work out the problem as well when you already know what it is. ALWAYS explain what you're trying to do, how you're trying to do it and what happens when you try. That third point is completely missing from your question. – John Sep 19 '22 at 09:41
  • MySql.Data.MySqlClient.MySqlException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near STAFF Finance Where ID="28" at line *This always say when i run my program – Hinata Sep 19 '22 at 09:42
  • Most likely you have been told that there's a syntax error in your SQL code but you haven't shown us that SQL code or even looked at it yourself. The VB code that builds the SQL code is not the SQL code. Look at the SQL code. You should absolutely be using parameters, as suggested above, but if you were to look at the code and see the problem, you'd get some idea of exactly why you should be using parameters by seeing the sort of problem it helps avoid. – John Sep 19 '22 at 09:43
  • No one should have to read the comments to understand the question. Don't put critical information in comments. Edit your question and provide the information there, where it should have been in the first place. – John Sep 19 '22 at 09:44
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 19 '22 at 16:53

1 Answers1

0

There are many problems in your code and if you look around this site I think you will find many partial answers that step by step will help you solve your problems. So I try to give you an answer where all the problems are examined, discussed and solved.

First problem: How do you handle the connection.
It seems that you have a global connection instance called con that you open with openCon. This is not a good approach and always a source of problems. You always need to check if the connection is closed properly or not. For example, in the code above you have forgot to close the connection in case of exception and this will lead to other exceptions in some code not related to this one. You keep resources on the server locked to you and this will decrease the performance of every one connection to that server.
I would change your openCon to this

 Public Function openCon() as MySqlConnection
      Dim con as MySqlConnection = new MySqlConnection(....here connection string ...)
      con.Open()
      return con
 End Function

This will create a new instance of the MySqlConnection every time you call this method Now you can remove the global connection instance and use the one returned by openCon in this way

 Using con As MySqlConnection = openCon()
    .... code that use the local con object

 End Using

This will close and destroy the connection even if an exception occurs inside the Using block and the ADO.NET libraries are smart enough to use a thing called Connection Pooling to reduce the time required to build and open a connection with the same connection string.

Second problem: The syntax error.
Looking at the point of the error suggested by the message I can see a field name composed by two words separated by a space. This is fine, but then you should remember that the sql parser cannot understand this and you need to help it enclosing the two words in a backtick character (ALT+096) so the parser understand that this is a single field name. Given the fact column names are an internal information of no concern for your end user then why use spaces in column names? If possible remove the space in column names.

Third problem: Sql Injection and other syntax errors
You are concatenating strings to build an sql command. But this is an easy target for wannabe hackers. Suppose that I write in your textBox1 this string instead of a First Name: Mario'; --
Then your command becomes

UPDATE emp_table SET FNAME = 'Mario'; -- xxxxxxxxxxxx

everything after -- is considered a comment and the query is still executable, but it changes every record in emp_table to have a first name equal to Mario. But the query could fail as well if someone writes a Last Name that contains an apostrophe like O'Leary just now the query is no more syntactically valid.
The solution to this is always one. Use Parameters.

Recap of changes to your code.

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

    Dim cmdText as String = "UPDATE emp_table SET FNAME = @fname, 
                             LNAME= @lname, AGE = @age, GENDER =@gender, 
                             `OFFICE STAFF` = @staff
                             Where ID =@id"

    Using con as MySqlConnection = openCon()
    Using cmd as MySqlCommand = new MySqlCommand(cmdText, con)
    Try
        cmd.Parameters.Add("@fname", MySqlDbType.VarChar).Value = textBox1.Text
        cmd.Parameters.Add("@lname", MySqlDbType.VarChar).Value = textBox2.Text
        cmd.Parameters.Add("@age", MySqlDbType.VarChar).Value = textBox3.Text
        cmd.Parameters.Add("@gender", MySqlDbType.VarChar).Value = gender
        cmd.Parameters.Add("@staff", MySqlDbType.VarChar).Value = combobox1.Text
        cmd.Parameters.Add("@id", MySqlDbType.VarChar).Value = txtID.Text
        cmd.ExecuteNonQuery()
        MsgBox("Suceessfully Updated Record")
        TxtID.Clear()
        TextBox1.Clear()
        TextBox2.Clear()
        TextBox3.Clear()
        RBMale.Checked = False
        RBFemale.Checked = False
        ComboBox1.Text = ""

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
    End Using
    End Using
End Sub     

In the recap I have added parameters for every single field that you want to update. But remember. Parameters should have a Type (The MySqlDbType here) that should match the type of the field and the value should be of the same type. For example it seems improbable that Age is a varchar field. So you should convert TextBox3.Text to an integer if the field is an integer.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • Thank you very much. I use your codes i replace the data types in thier perspective data types but the always problem is they always say that i having SQL syntax, check the manual that corresponds to your MySQL server version for the right syntax to use near `Where `ID = 0 ` at line 1 – Hinata Sep 20 '22 at 01:31
  • Where does that backtick after "id = 0" come from? – Steve Sep 20 '22 at 06:26
  • Thank you. I ran my program the problem is lack of back tick hehe. – Hinata Sep 20 '22 at 09:51