问题描述:

I have a strange problem trying to connect to an SQL server. Using Visual Studio I can connect without any issues using the database explorer, create queries and get results back. Using the connection string from these connections fails to connect when running through C# code, I get an error:

Network error 26.

I have tried all the usual suspects: firewall, connection string, permissions etc. and am now totally frustrated.

The version of Visual Studio VS Express for Desktop 2015. I have tried System.Data.SQL, System.Data.ODBC, entity framework and everything that uses any C# code fails.

Can anyone explain why connection via VS will work but a simple connection object in C# fails?

P.S. I'm not a professional programmer just a little healthcare worker trying to improve of little lab.

Thanks

The working connection string is 'Server=server name\instance;Initial Catalog=table;Persist Security Info=True;User ID=my name; Password=pwd;'. Copying this to C# code fails to make the connection (as above). I have tried SQLCommandBuilder and failed. The server is another machine and not a local DB.

Example connection code :

private void OpenConnection()

{

string connStr = @"Server=<server name>\<instance>;Initial Catalog=<table>;Persist Security Info=True;User ID=<my name>; Password=<pwd>";

try {

using (SqlConnection conn = new SqlConnection(connStr))

{

conn.Open();

}

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

网友答案:

Besides the connection string, It'd be of great help if you post the type of connection you're attempting too. I believe these are the models for the three more common types of connection strings:

Standard Security:

Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;

Trusted Connection

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

Connection to a SQL Server instance

Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;
网友答案:

maybe your connection string is not valid, first of all for assurance to have a valid connection string make it with a "udl" file. for creating udl, create a notepad text file and change extension from "txt" to udl, double click on it, and it show you "data link properties" so set it up, it make your connection string and even you can test connection status.

相关阅读:
Top