Reputation: 218
I tried too many times but insertion doesn't work! Please help me..
codes:
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO mytbl(Id, Nav) VALUES('yek','du')", conn); //yek and du are examples
//Following command doesn't work, too
//"INSERT INTO mytbl(Id, Nav) VALUES('"+tb.Text+"','"+tb2.Text+"')"
cmd.ExecuteNonQuery();
conn.Close();
Upvotes: -2
Views: 1375
Reputation: 11
Your code is working but the db(.mdf) is getting copied to \bin\debug directory first and the app is using that one(\bin\debug\Database1.mdf). Use the following code to get the db (.mdf) path which is present at your App root directory.
string path = AppDomain.CurrentDomain.BaseDirectory.ToLower().Replace("\\bin", "").Replace("\\debug", "").Replace("\\release", "").TrimEnd('\\');
string conStr = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=" + path + "\\Database1.mdf;Integrated Security=True";
Upvotes: 1
Reputation: 755073
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf
file (from your App_Data
directory to the output directory - typically .\bin\debug
- where you app runs) 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...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Upvotes: 2