Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

c# - Data is not inserting into table?

My table name is Customer. It has four columns

CustomerId
CustomerName
CustomerAddress
PhoneNo

This is my c# code. I am not getting any exceptions and data is not inserting into database.

string connString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\VictoryDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection myConnection = new SqlConnection(connString);

try
{
   myConnection.Open();
   string query = "insert into Customer(CustomerName,CustomerAddress,PhoneNo) values (@CustNm,'@CustAdd',@Ph)";
   SqlCommand myCommand = new SqlCommand(query,myConnection);
   myCommand.Parameters.AddWithValue("CustNm",Print[0].CustomerName);
   myCommand.Parameters.AddWithValue("CustAdd",Print[0].Address);
   myCommand.Parameters.AddWithValue("Ph",Print[0].Telephone);

   Console.WriteLine(Print[0].Telephone);

   myCommand.ExecuteNonQuery();
   myConnection.Close();
}
catch (Exception e)
{
   Console.WriteLine(e.ToString());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I've said before on this site - 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

  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. VictoryDatabase)

  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=VictoryDatabase;Integrated Security=True
    

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...