-1

I'm a student of Computer science and I'm working on some C# applications at home for practice. I have created a local database (.mdf) and I'm trying to add some data through text boxes.

// I have this code for sending the data to the database which I have already connected with.

    private void BtnSubmitD_Click(object sender, EventArgs e)
    {
        cmd.CommandText = "inster into st(Student's ID) values ('"+txtID.Text+"' )";
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        MessageBox.Show("Data has beed record.");
    }

enter image description here

This error message keeps coming up:

system.data.sqlclient.sqlexception 'incorrect syntax near the keyword 'into'.' Unclosed quotation mark after the character string ' )'.'

pppery
  • 3,731
  • 22
  • 33
  • 46
Marty SC
  • 13
  • 6
  • Once you get your `insert` query working you should see what happens when you type the following into the text box: `'); drop table st;` – AlwaysLearning Jul 31 '19 at 02:55
  • 1
    maybe do what @AlwaysLearning suggest with a separate test table. In case you have important data in it... – Ryan Tan Jul 31 '19 at 02:59
  • @MartySC Yes, I was being facetious. You should **never ever** trust user input, nor should you construct SQL queries with user input. Look up how to use *Parameterized Queries*, e.g.: [SqlCommand.Parameters Property](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8) – AlwaysLearning Jul 31 '19 at 03:21

1 Answers1

1

You can correct your query from

inster into st(Student's ID) values ('"+txtID.Text+"' );

To

insert into st (`Student's ID`) values ('"+txtID.Text+"' );

Use the `` Symbol to enclose your column names, if your column has spaces and ' in it.

Also, your query is prone to Mysql injections. Do take that into consideration.

Ryan Tan
  • 344
  • 2
  • 11
  • That should more or less fix the issue with your query. Do let me know if it works or not for you. – Ryan Tan Jul 31 '19 at 02:51
  • Hey Ryan, I'm glad for ur help but unfortunately, I have to tell u that it's not making any difference. See again please my error message about the third line "" cmd.ExecuteNonQuery(); "" – Marty SC Jul 31 '19 at 16:45
  • The error message from your question states there is a syntax error in the query. the solution I offered should be free of any syntax. Please check, if `st`(Your Table) and `Student's ID` (Your Column) is the actual reference saved in your Database. I suggest putting a breakpoint before it executes, mouse over .CommandText copy the query and try it on your Mysql-Workbench(or equivalent) – Ryan Tan Aug 01 '19 at 02:13