shiroi
shiroi

Reputation: 1

SqlConnection error vs2015 with C#

I work with VS 2012 and SQL Server 2012. When I changed to VS 2015 & SQL Server 2014, my SqlConnection didn't work and causing errors that the servers could not be found.

My code:

SqlConnection cn = new SqlConnection(@"Data Source=(local); Initial Catalog=jood; Integrated Security=true;MultipleActiveResultSets=true");

public Form1()
{
    cn.Open();
    cn.Close();
    InitializeComponent();
}

Error

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: 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)

Upvotes: 2

Views: 129

Answers (2)

DAVID OLASUPO
DAVID OLASUPO

Reputation: 39

Check to be sure that "Initial Catalog=jood; is the same as on your sql DB. The error basically means it can't find that DB you're trying to connect to.

Upvotes: 0

Horkrine
Horkrine

Reputation: 1407

If you plan on declaring your SqlConnection property outside of a method, you need to set an access qualifier (public, private, whatever). Try using localdb instead of local as well. Do your initialization before you do your connections.

If this still isn't working, check your Sql configuration settings and make sure you have access to the database with your windows credentials instead of just an sql login like sa/sa

public SqlConnection cn = new SqlConnection(@"data source=(localdb);initial catalog=jood;Integrated Security=true;MultipleActiveResultSets=true");

public Form1()
{
    InitializeComponent();

    cn.Open();
    cn.Close();
}

Tried this just now with VS2015 and SQL Server 2014 - Worked fine.

EDIT: If you can, try explicitly telling it your server name rather than using localdb.

Upvotes: 1

Related Questions