This is my code below. The program runs fine. I don\'t get any exceptions. But in the end, the table doesn\'t contain the newly inserted row. (Note, the connection string is co
The primary issue causing the problem you're asking about is that the connection is never opened.
You can't execute the command until the connection is open.
There are a few other issues:
Several best practices are listed here. Here's an excerpt on using the "using" statement properly.
Use the "Using" Statement in C#
For C# programmers, a convenient way to ensure that you always close your Connection and DataReader objects is to use the using statement. The using statement automatically calls Dispose on the object being "used" when leaving the scope of the using statement. For example:
//C#
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}