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 correct).
string Name = "myname";
string Age = "myage";
string sql = "INSERT INTO Student (Name, Age) VALUES ('" + Name + "','" + Age + "')";
SqlConnection conn = new SqlConnection(ConfigHelper.GetConnectionString());
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
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
.mdffile and most likely, yourINSERTworks 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.mdffile 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:
and everything else is exactly the same as before…