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:
- I see no error handling, which would help you identify the error. There's probably something swallowing your errors so you don't see them.
- You're contencating strings, which leaves you open to SQL Injection. I strongly recommend learning about parameterized queries.
- You're not using a using statement for your connection, which would ensure automatic closing and disposal
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));
}
}
AttachDbFileName=.....construction - that's prone to errors like this... but we need to know for sure.