Search code examples
c#asp.netsql-serverlocaldb

Insert data into Visual Studio LocalDB in ASP.NET C#


I have a Windows web application and have created a .mdf file in the App_Data folder and I am trying to insert data into the tables already created.

It is able to retrieve codes with a basic SELECT * statement, but I can't insert data, this is the code I have:

private void Update(string username)
{
    SqlConnection con = new SqlConnection(@"MYSQLCONNECTION");
    con.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    string bcd = "INSERT INTO NameList(name) VALUES (@paraUsername)";
    cmd = new SqlCommand(bcd, con);
    cmd.Parameters.AddWithValue("@paraUsername", username);

    cmd.ExecuteNonQuery();
    list.Update();

    con.Close();
}

This code has worked for me in the past, but this time round it does not work. There is no error shown, but the data is not inserted into the table.

This is how I call the method in side my button_click method:

Update(tbName.text);

What might be the problem?


Solution

  • Assuming you have a

    AttachDbFileName=......
    

    section in your connection string - then this is a known issue:

    The whole 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

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

    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=YourDatabase;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.