Tuesday, July 14, 2009

How to insert new record into database - the hassle-free way

The code is written in C# and it does not make use of DataAdapter, DataSet and all unnecessary objects..
using System.Data.SqlClient;
using System.Data;

// open the database connection
String connectionString = "..."; // get from the web. config file, and use connectionstrings.com as reference
SqlConnection cn = new SqlConnection(connectionString);
try
{
    cn.Open();
    SqlCommand cmd = new SqlCommand("INSERT INTO CodeMaintenance (question, answer) VALUES ('hello', 'world')", cn);
    cmd.ExecuteNonQuery();
    cn.Close();
}
catch (Exception ex){ // print error message }

No comments:

Post a Comment