how to insert data into sql server in asp.net website?

.net, asp.net, c#, sql-server

Solution

Okay, let's fix this code up just a little. You're getting there:

var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(@City,@FName,@LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
    using (SqlCommand cmd = new SqlCommand(cmd, cnn))
    {
        cmd.Parameters.AddWithValue("@City",txtCity.Text);
        cmd.Parameters.AddWithValue("@FName",txtFName.Text);
        cmd.Parameters.AddWithValue("@LName",txtLName.Text);

        cnn.Open();
        cmd.ExecuteNonQuery();
    }
}

A couple things to note about the modified code.

- It's leveraging the `using` statement to ensure that resources are properly disposed.

- It's parameterized to ensure that SQL Injection isn't a possibility.

- It's not storing a connection object anywhere, get rid of that stored connection.

Problem

I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website. The code in .aspx.cs file is ``` public partial class _Default : System.Web.UI.Page { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { conn.Open(); } protected void btnInsert_Click(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand("insert into Insert values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn); cmd.ExecuteNonQuery(); conn.Close(); Label1.Visible =true; Label1.Text = "Your data inserted successfully"; txtCity.Text = ""; txtFName.Text = ""; txtLName.Text = ""; } ``` } `

Original source