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));
}
}
First of all: start using parametrized queries! Otherwise your code is always open to SQL injection attacks - not something you want to have to deal with.
Assuming you are using this feature (depends on the connection string, which you haven't shown us in the original question): the whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf
file and most likely, your INSERT
works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close()
call - and then inspect the .mdf
file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. VictoryDatabase
)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=VictoryDatabase;Integrated Security=True
and everything else is exactly the same as before...