1

There are text boxes in my windows form called txtName,txtAdd,txtTel & txtEmail. I need to add the text in this text boxes to my database table. My table name is "Table". I used the following code to add those text to my table. The table columns are Name,Address,Tel No. & email.

 SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\user\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database1.mdf;Integrated Security=True");

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            String name = txtName.Text;
            String add = txtAdd.Text;
            String tel = txtTel.Text;
            String email = txtEmail.Text;

            String SqlQuery = "insert into Table values('" + name + "','" + add + "','" + tel + "','" + email + "')";
            SqlCommand cmnd = new SqlCommand(SqlQuery, con);
            con.Open();
            cmnd.ExecuteNonQuery();
            MessageBox.Show("Saved Successfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch
        {
            MessageBox.Show("Error occured while saving", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        finally
        {
            con.Close();
        }
    }

I typed some texts and pressed button1. But everytime I get the "Error occured while saving" message box. I can't understand the reason for that. I used varchar data type for all of the fields in my table. I am using visual studio 2012 express. Please help me to solve this problem.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • 4
    This catch is useless. Change it to _catch(Exception ex) { MessageBox.Show(ex.Message);}_ and tell us what you get – Steve May 20 '16 at 16:22
  • @Steve, your comment should be the answer. – Jodrell May 20 '16 at 16:24
  • 2
    It appears that your sql is wrong. Also, you do not want to string concat text fields into your query due to sql injection. Look into SqlParameters. – Stephen Brickner May 20 '16 at 16:24
  • maybe you typed `";GO DROP Table;GO"` in to one of the text boxes? – Jodrell May 20 '16 at 16:27
  • I suspect that there is a problem with that INSERT INTO without columns' names – Steve May 20 '16 at 16:27
  • @steve, then there is a red line under the message – user6333477 May 20 '16 at 16:28
  • @Steve its impossible to know without knowing the schema of Table. – Jodrell May 20 '16 at 16:28
  • @Jodrell, I didn't understand what you say – user6333477 May 20 '16 at 16:29
  • okay, I'll try and be helpful. An exception is being thrown, we need to know what it is. Change `catch` to `catch(Exception ex)` then we will get the exception is the catch block. Change `"Error occured while saving"` to `ex.Message`, then we will see what the exception is. – Jodrell May 20 '16 at 16:32
  • 1
    Or just let crash the code removing the catch block and let the exception show itself – Steve May 20 '16 at 16:34
  • very likely, you have the wrong number or type of values or they are in the wrong order. – Jodrell May 20 '16 at 16:34
  • Should I type that as MessageBox.Show(ex."Error occurred while saving")? Then there is a red line under the part within " ". – user6333477 May 20 '16 at 16:35
  • no `MessageBox.Show(ex.Message)`, `Message` is a property of an `Exception`. – Jodrell May 20 '16 at 16:36
  • Same with that also. So I typed as ("error occurred while saving" + ex). Then there is a very big message box with a message like "Incorrect syntax near the 'Table'" and so on – user6333477 May 20 '16 at 16:39
  • edit the question and include all that text – Jodrell May 20 '16 at 16:41
  • 1
    I am guessing you don't have a table called `Table` or more likely the very fact it is called "Table" and not escaped is causing the problem. If this were MySQL I could tell you the delimiters, but it appears that is not actually the case. – Uueerdo May 20 '16 at 16:41
  • 1
    change `Table` to `\`Table\`` if you are using mysql, `[Table]` for Sql Server. – Jodrell May 20 '16 at 16:42

1 Answers1

1

The problem is caused by your string concatenation of values to form an sql command. This is well known as a source of bugs and in a potential security risk called Sql Injection. Otherwise you could receive an error when using an INSERT INTO table without specifying the column names. If you don't write the columns then you should pass a value for every column of your table and in the exact order expected by your table.

You should use a parameterized query

public string conString = @"Data Source=(LocalDB)\v11.0;
 AttachDbFilename=c:\users\user\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database1.mdf;
 Integrated Security=True";


private void button1_Click(object sender, EventArgs e)
{
    try
    {
        String name = txtName.Text;
        String add = txtAdd.Text;
        String tel = txtTel.Text;
        String email = txtEmail.Text;
        String SqlQuery = @"insert into [Table] 
                            values(@name,@add,@tel,@mail)";

        using(SqlConnection con = new SqlConnection(conString))
        using(SqlCommand cmnd = new SqlCommand(SqlQuery, con))
        {
             con.Open();
             cmnd.Parameters.Add("@name", SqlDbType.NVarChar).Value = name;
             cmnd.Parameters.Add("@add", SqlDbType.NVarChar).Value = add;
             cmnd.Parameters.Add("@tel", SqlDbType.NVarChar).Value = tel;
             cmnd.Parameters.Add("@email", SqlDbType.NVarChar).Value = email;
             cmnd.ExecuteNonQuery();
         }
     }
     catch(Exception ex)
     {
          MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
}

Notice also that I have moved your disposable objects inside a using block to ensure proper disposing of the objects SqlConnection and SqlCommand

EDIT If you really have a table in your database named Table then you need to put square brackets around that name because it is a reserved word in Sql Server (or better, change that name to something more meaningful in relation to the data stored there)

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • 2
    As you know, fixing the vulnerability, while desirable, won't actually fix the schema mismatch. – Jodrell May 20 '16 at 16:39
  • @user6333477 change your code to this and see what happens – Jodrell May 20 '16 at 16:40
  • I know but the OP needs a reference code to start with – Steve May 20 '16 at 16:42
  • There is a red line under conString – user6333477 May 20 '16 at 16:48
  • Check the ErrorList window and report/fix your syntax error – Steve May 20 '16 at 16:52
  • When the program is running there is a error message like "incorrect syntax near the table" – user6333477 May 20 '16 at 17:18
  • Did you put the name of the table between square brackets? – Steve May 20 '16 at 17:22
  • Well, good to know, but I repeat myself, you shouldn't name your table in that way. It is a lot confusing and a source of time wasting problems. – Steve May 20 '16 at 18:16
  • Ok. But the software doesn't let me to change the table name it is there as table. How to change the name? I don't know – user6333477 May 20 '16 at 20:37
  • Well this is an administrative task, not something you do from code. Usually Sql Server comes with its administrative tool called Sql Server Management Studio. Here you have a lot of options to change the table name. Using right click and rename, using SQL system stored procedure sp_rename. – Steve May 20 '16 at 20:47
  • Steve I need to delete some items from my table according to the email. What should I do now? – user6333477 May 22 '16 at 10:27
  • Can I do this with this conString method? – user6333477 May 22 '16 at 10:29
  • Please post a new question with the relative details. It is not a welcome practice on SO to add new problems to an old question. You can always add a link in your new question to this one if there is something that need to be explained – Steve May 22 '16 at 11:14