1

I keep on getting the problem

"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll" "on SDA.SelectCommand.ExecuteNonQuery();".

Whats the problem here?

SqlConnection con = new SqlConnection(@"Data Source=LAPTOP-LD5OK96E\SQLEXPRESS;Initial Catalog=TRANSACTION_RATE TABLE; Integrated Security=True");

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        con.Open();
        String query = "INSERT INTO TRANSACTION_RATE TABLE (Trans_id,Transaction_type,Transact_rate,Transact_description) VALUES('" + textBox1.Text + "','" + textBox2.Text + "''" + textBox3.Text + "''" + textBox4.Text + "')";
        SqlDataAdapter SDA = new SqlDataAdapter(query, con);
        SDA.SelectCommand.ExecuteNonQuery();
        con.Close();
        MessageBox.Show("Success!");
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
All Mixtape
  • 31
  • 1
  • 4
  • 2
    I'm pretty sure this `INSERT INTO TRANSACTION_RATE TABLE` is not correct. I guess `TABLE` is the bit you copy/pasted wrongly but once you fixed that you're still in for lots of trouble if that code ever makes it into production.https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work?rq=1 – rene Apr 28 '20 at 08:57
  • You have two separate problems in your question. You should a) Avoid concatenating strings because is a security risk called SQL Injection and b) your "TRANSACTION_RATE TABLE" should be escaped so SQL Server knows what the table name is. Check this [related answer](https://dba.stackexchange.com/questions/22989/escaping-t-sql-keywords) – Cleptus Apr 28 '20 at 09:00

1 Answers1

3

You have one stray TABLE keyword after your table's name, you need to remove it. as a second note, you need to be aware that this kind of string concatenation is avoided and it is open to SQL Injection attack:

String query = "INSERT INTO TRANSACTION_RATE (Trans_id,Transaction_type,Transact_rate,Transact_description) VALUES (@Trans_id, @Transaction_type,@Transact_rate, @Transact_description)";


SDA.SelectCommand.Parameters.Add("@Trans_id", SqlDbType.NVarChar, 50).Value = textBox1.Text;
SDA.SelectCommand.Parameters.Add("@Transaction_type", SqlDbType.NVarChar, 50).Value = textBox2.Text;
SDA.SelectCommand.Parameters.Add("@Transact_rate", SqlDbType.NVarChar, 50).Value = textBox3.Text;
SDA.SelectCommand.Parameters.Add("@Transact_description", SqlDbType.NVarChar, 50).Value = textBox4.Text;

In case your table was named in fact TRANSACTION_RATE TABLE you should escape the name like this:

INSERT INTO [TRANSACTION_RATE TABLE] ....
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • SIR, IT WORKS!!! What I did was, I rolled back the codes to SqlDataAdapter SDA = new SqlDataAdapter(query, con); and SDA.SelectCommand.ExecuteNonQuery();. After that its done!! I'm very thankful that you are there, you the best sir! – All Mixtape Apr 28 '20 at 11:18