3

I installed SQL Server and Visual Studio and tried to do my university project.

I can connect to SQL Server in Management Studio but can not connect in Visual Studio!

  • Remote connecting is enabled
  • all services are running
  • and everything is ok but I dont know why I get this 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 the ...

What's wrong with this code?

 SqlConnection sqcon = new SqlConnection("Data Source=.;Initial Catalog=Badan_Sazi;Integrated Security=True");

 SqlCommand com = new SqlCommand();
 com.Connection = sqcon;
 com.CommandText = "SELECT tbl_morabi.family   as 'lname'  FROM tbl_morabi";

 com.Connection.Open();

I also tried ., localhost, my pc name ... same error anyway

  • Visual Sudio 2012
  • SQL Server Express 2012
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
hrh_fourtyseven
  • 33
  • 1
  • 1
  • 4

2 Answers2

9

SQL Server Express defaults to a SQLEXPRESS instance name

So try to use .\SQLEXPRESS or (local)\SQLEXPRESS as your server+instance name.

And if that doesn't work: what server name do you use in Management Studio to connect to your SQL Server instance?? Use that name!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

You can check your connectionString. It should be like that below.

<connectionStrings>
<add name="SampleConnectionString" connectionString="Data Source=machinename\instancename;Initial Catalog=AdventureWorks;Integrated Security=SSPI;Min Pool Size=5;Max Pool Size=60;Connect Timeout=30″ providerName="System.Data.SqlClient"/>
</connectionStrings>
nevra
  • 418
  • 1
  • 7
  • 21
  • thank you. visual studio does not accept mymachine\instancename because of syntax error ! should I type it different? – hrh_fourtyseven Feb 19 '15 at 09:29
  • 1
    If you use default settings, you should write `.\SQLEXPRESS`, for other things you should check SQL SERVER Server Name – nevra Feb 19 '15 at 09:31
  • Use `Data Source=(localdb)\\MSSQLLocalDB` instead. See: https://stackoverflow.com/a/52838019/1548275 – Jari Turkia Mar 20 '20 at 10:09