Thursday, July 5, 2012

Write to a SQL Database using C#

using System.Data.SqlClient;

private void btn_ok_Click(object sender, EventArgs e)
{
            //write to db
            string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Thisal Lekamge\Desktop\Shohan\new\ChainMan.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("INSERT INTO Item (itemName, itemDescription) VALUES (@itemName, @itemDescription);");

                cmd.CommandType = CommandType.Text;
                cmd.Connection = connection;

                cmd.Parameters.AddWithValue("@itemName", textBox3.Text);
                cmd.Parameters.AddWithValue("@itemDescription", textBox5.Text);

                connection.Open();

                cmd.ExecuteNonQuery();

                connection.Close();
              }

}

No comments:

Post a Comment