Search code examples
c#.netsql-servervisual-studioado

How to establish SQL Connection in Visual Studio using local mdf file


I'm new to coding. I'm attempting to access a SQL Server file through WPF / C# and I am having trouble getting in the correct string, I believe. I do not yet fully understand SQL logins, but here is the code I have now, which I believe as close to correct as I can get on my own:

string CS = @"Data Source=(LocalDB)\v11.0; Integrated Security=true; AttachDbFileName=C:\Users\Madison\source\repos\TheRealStudyBot\TheRealStudyBot\TestingData.mdf";

SqlConnection con = new SqlConnection(CS);

SqlCommand cmd = new SqlCommand("CREATE TABLE table1 (PK int, Name nvarchar(255), PRIMARY KEY *PK),);", con);

con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
con.Close();

This code is under public MainWindow(), after InitializeComponent(). The file path should be correct. The database is empty. I get this exception:

Win32Exception: Unknown error (0x89c50118)

Ran it once more and I think I may have accidentally altered my debug settings because now it also provides a window stating

The solution does not contain the specified document

(along with plenty of other jargony-code-exception-results-text). I don't see where I'm going wrong. Please help!


Solution

  • If you are on Visual Studio 2019,

    1. Double Click on your LocalDB which opens Server Explorer
    2. Clicking on your database, On the properties tab shows the connection string.
    3. Copy that & Paste on CS!

    And the Normal Connection String Format For LocalDB is,

    Data Source=Your_DataSource;Initial Catalog=YourDatabaseName;Integrated Security=True;Pooling=False