简体   繁体   中英

Unable to connect to a Local DB (mdf) from C# form application

I tried to play with Database creation and queries. In order to do that I started a C# form application, added a Database Service then added a Table with some values, then I wanted to use some code to retrieve those values. Here's the code:

string conn = "data source = ./SQLEXPRESS; AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True";

SqlConnection sql = new SqlConnection(conn);

sql.Open();
MessageBox.Show("Connection Opened");
sql.Close();

Sadly the program throws an exception when comes to the open because it seems it cannot find the Database...

"Server not found or not accessible"

I don't know what is the problem, what would you suggest?


Ok, it seems to work now but I get an incorrect syntax for my query

string conn = "Server=(LocalDB)\\v11.0; AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf; Integrated Security=True;Connect Timeout=30;User Instance=False";

        string queryString = "SELECT * FROM Table";
        SqlConnection sql = new SqlConnection(conn);

        sql.Open();
        SqlDataAdapter adapter = new SqlDataAdapter();
        SqlCommand command = new SqlCommand(queryString, sql);

      /* --->here I get the error*/ command.ExecuteNonQuery();

        DataSet data = new DataSet();
        adapter.Fill(data);
        MessageBox.Show(data.ToString());
        sql.Close();

It looks like the data source part your connection string is wrong. It should be:

"Data source=.\\SQLEXpress"

Complete:

string conn = "Data source=.\\SQLEXpress; AttachDbFilename=C:\\Users\\Asus\\Desktop\\RobaMia\\SQLSERVER\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf; Integrated Security=True;Connect Timeout=30;User Instance=True";

https://www.connectionstrings.com/sql-server/

As an additional note, you may be best off placing this in an app.config or web.config file just encase you reference the connection string multiple times and later you decide to change the value of it.

Have you tried(LocalDB), instead of SQLExpress?

"Server=(localdb)\\Test;Integrated Security=true;AttachDbFileName= myDbFile;"

http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM