When I create a database I get an error message telling me "the database already exists, choose another" when I know it doesn't

Viewed 44

I want to create a database but allow a user to select what folder to put it in. The code I've come with is:

  string dirLoc = "";

  FolderBrowserDialog fldr = new FolderBrowserDialog();
  fldr.Description = "SELECT LOCATION OF PASSWORD DATABASE\n(Recommendation: select a portable drive for security reasons.)";
  fldr.ShowNewFolderButton = true;
  fldr.RootFolder = Environment.SpecialFolder.MyComputer;

  if (fldr.ShowDialog() == DialogResult.OK)
  {
    dirLoc = fldr.SelectedPath;

    try
    {
      SqlConnection conn = new SqlConnection(@"Server=(LocalDB)\MSSQLLocalDB;Integrated security=SSPI;database=master");


      string query = "CREATE DATABASE LockKeyDB ON PRIMARY " +
        "(NAME = LakDB_Data, " +
        "FILENAME = '" + dirLoc + "\\LakDB.mdf', " +
        "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
        "LOG ON (NAME = LakDB_Log, " +
        "FILENAME = '" + dirLoc + "\\LakDBLog.ldf', " +
        "SIZE = 1MB, MAXSIZE = 5MB, FILEGROWTH = 10%)";

      SqlCommand cmd = new SqlCommand(query, conn);
      conn.Open();
      cmd.ExecuteNonQuery();
      conn.Close();
    }
    catch(Exception ex)
    {
      MessageBox.Show(ex.ToString(),"LakTools - ERROR", MessageBoxButtons.OK,MessageBoxIcon.Error);
    }

When I run the code I get an exception thrown out like this: This is the error I keep getting

Now it looks like The SQL Server I'm using (SQL Server 2019) is saving table names because I'm still testing the program, and if I change the database name it works no problem. But, I'm still in the test mode and I don't want to keep changing the database name.

So is there anyway to get around this and clear it up?

1 Answers

You are attemtpting to create different databases by separating the underlying mdf file in a different folders. However, you're still giving them all of the same database NAME of LockKeyDB. You can't have the same database NAME multiple times on the same server, regardless of them having different storage locations. You'll have to give each DB a unique name.

Example:

string query = "CREATE DATABASE " + uniquecode + "LockKeyDB ON PRIMARY " +
Related