简体   繁体   中英

Connecting to SQL Server 2014 via console application does not work

I'm trying to read out values from my database. I'm pretty sure that the method I use is correct. Also my SQL Server 2014 allows remote access.

Nevertheless when I run my application I get an error.

System.Data.SqlClient.SqlException: 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: SQL Network Interfaces, error: 25 - Connection string is not valid)

My code:

private void DatabaseUpgradeCheckForMSSQL()
{ 
    SqlConnection sqlCon = new SqlConnection("Data Source=VBKSQL2014MSSQL\\MSSQLSERVER; Initial Catalog=dwworkflowengine; User ID=sa; Password=<Password>;");
    SqlDataAdapter sqlda = new SqlDataAdapter("Select * from Changesets", sqlCon);

    DataTable dtbl = new DataTable();
    sqlda.Fill(dtbl);

    foreach (DataRow row in dtbl.Rows)
    {
        Console.WriteLine(row["Number"]);
    }

    Console.ReadKey();
}

If you're connecting to the default, unnamed instance of SQL Server, which does have the internal "ID" of MSSQLSERVER , you must not use that internal ID as the instance name.

So instead of this:

SqlConnection sqlCon = new SqlConnection("Data Source=VBKSQL2014MSSQL\\MSSQLSERVER; Initial Catalog=dwworkflowengine; User ID=sa; Password=<Password>;");

try this:

SqlConnection sqlCon = new SqlConnection("Data Source=VBKSQL2014MSSQL;Initial Catalog=dwworkflowengine;User ID=sa;Password=<Password>;");

And please - as a Best Practice - do NOT use the sa account for your work!! Use integrated security, or a separate account - sa should NEVER be used in your real life work!

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