0

I have created a game but I want to save the users to a SQL Server database. But once I close the form, all the records are lost. But when I go back to a different form and don't close the application, I get all the records.

This is my connection string in app.config

Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\HighScores.mdf;Integrated Security=True

Code:

connectionString = ConfigurationManager.ConnectionStrings["ChickenBlaster.Properties.Settings.user_dataConnectionString"].ConnectionString;

public SqlConnection conn;
string connectionString;

conn = new SqlConnection(connectionString);

conn.Open();

string query = ("INSERT INTO dbo.Highscore (id,naam) VALUES (@id, @sam)");

SqlCommand cmd = new SqlCommand(query, conn);

cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@naam", txtUsername.Text);

cmd.ExecuteNonQuery();

conn.Close();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sam
  • 63
  • 2
  • 7

1 Answers1

5

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 (if you haven't done that already)

  2. install SQL Server Management Studio

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

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

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