1
String nam = name.Text;
SqlConnection cn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\test.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("INSERT INTO tab(tname)VALUES(@val)", cn);
cmd.Parameters.AddWithValue("@val", nam);
cn.Open();
int cnt = cmd.ExecuteNonQuery();
MessageBox.Show("Message:" + cnt);
cn.Close();

This is my code. The message shows Message:1. But the value is not inserted in database test. Table name is tab with column name tname.

What will possibly be wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • you are missing `;` at last of the connection string. I am not sure. – Mr_Green Oct 29 '12 at 06:31
  • return 1 means the code actually inserts into database, maybe you seems to need to refresh management studio to see actual result – cuongle Oct 29 '12 at 06:34

1 Answers1

0

This whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file (to the output directory where Visual Studio is running your app from) 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 cn.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

  1. install SQL Server Express (and you've already done that anyway)

  2. install SQL Server Management Studio Express

  3. create your database in SSMS Express, give it a logical name (e.g. TestDB)

  4. 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=TestDB;Integrated Security=True
    

    and everything else is exactly the same as before...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459