Marco Romano
Marco Romano

Reputation: 11

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();

Upvotes: 1

Views: 1071

Answers (2)

Darren
Darren

Reputation: 70728

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.

Upvotes: 2

Thiago Avelino
Thiago Avelino

Reputation: 828

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

Upvotes: 0

Related Questions