Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Insert not working

Tags:

c#

sql

asp.net

When the event Button is pressed nothing updates in the SQL Table and no errors display.

protected void SubmitBTN_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Matt\Documents\coffeeShop.mdf;Integrated Security=True;Connect Timeout=30");

    String coffeeName = NameTXT.Text;
    String coffeeGrid = GrindTXT.Text;
    String coffeeOrigin = OriginTXT.Text;
    String coffeePrice = PriceTXT.Text;
    String coffeeQty = QuantityTXT.Text;
    String coffeeRRP = RRPTXT.Text;

    SqlCommand comm = new SqlCommand("INSERT INTO Table (coffeeName, coffeeGrid, coffeeOrigin, coffeePrice, coffeeQty, coffeeRRP) VALUES ('%" + coffeeName + "%','%" + coffeeGrid + "%','%" + coffeeOrigin + "%','%" + coffeePrice + "%','%" + coffeeGrid + "%','%" + coffeeQty + "%','%" + coffeeRRP + "%' ", conn);

    conn.Open();
    //SqlDataReader reader = comm.ExecuteReader();

    //lblDBData.Text += "<table border=0>";
    //while (reader.Read())
    //{
    //    lblDBData.Text += "<tr>";
    //    lblDBData.Text += "<td>" + reader["coffeeName"] + "</td>";
    //    lblDBData.Text += "</tr>";
    //}
    //lblDBData.Text += "</table>";

    //reader.Close();
    conn.Close();                     
}

Any advice would be much appreciated, Many thanks

like image 590
Matt Jones Avatar asked Dec 03 '25 02:12

Matt Jones


1 Answers

Add:

comm.ExecuteNonQuery();

After:

conn.Open();

By the way, you would want to use parameters instead of " + parameter + " on query to avoid sql injection. Read this:

http://www.csharp-station.com/Tutorial/AdoDotNet/Lesson06

like image 83
Retired_User Avatar answered Dec 04 '25 14:12

Retired_User



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!