Rajesh Pandey

Rajesh Pandey

  • NA
  • 12
  • 9.6k

Getting Error while connecting the database

Aug 27 2011 1:15 AM
Dear Sir,
 I am getting error while connecting to the database.
Here I have created the database named MyWorkers.mdf by using the visual C# express edition by selecting the project menu and then add new item and then selecting the service based database option.
Now while I want to connect to that database using code I am getting error.
My code is as follows:
private void Form1_Load(object sender, EventArgs e)
{
string source="server=.//SQLEXPRESS; Integrated security=SSPI ;   database=MyWorkers.mdf ;
sqlconnection conn =new sqlconnection(source);
conn.Open();
MessageBox.Show("Database is connected");
Conn.Close();
}
While compiling this code I am getting following error:
Error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

But When I write following code I can successfully connect the database what the main problem please some body help me plzzzzzzzzz.


private void Form1_Load(object sender, EventArgs e)
{
  string source =  "DataSource=.\\SQLEXPRESS;AttachDBFilename=C:\\MyWorkers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
  SqlConnection conn = new SqlConnection(source);
  conn.Open();
  MessageBox.Show("Database is connected");
  conn.Close();
}


Answers (6)