A network-related or instance-specific error occurred while establishing a connection to SQL Server when starting the program on another computer

一个人想着一个人 提交于 2021-02-11 12:55:49

问题


I need help solving this problem. I created the application installer using MS Visual Studio Installer Projects and ran it on another device. There were no versions of LocalDB that installed on my computer (2016 and 2017) in the prerequisites, so I had to download the SQL Server 2017 LocalDB on another computer manually. After that, when I started the program I received the following error.

Database files were automatically placed during installation in the folder Documents

I changed the connection string as follows:

string dbPathMyDoc = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string dbPath = Path.Combine(dbPathMyDoc, "myprojectAppData"); 
AppDomain.CurrentDomain.SetData("DataDirectory", dbPath);

Database path

So it seems to me that the problem is not the connection string, but then what?


回答1:


I make sample fixed problem for all project when create ny winforms & localdb

You can create 2 ConnectionString in App.config file

App.config

<add name="DevConnectionString"
      connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True"
      providerName="System.Data.SqlClient" /> <!--  *1* Use when publish project--> 

<!--<add name="AppConnectionString"
        connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='E:\My Projects\MyDatabase.mdf';Integrated Security=True"
        providerName="System.Data.SqlClient" />-->
<!--*2* Use for development-->
  • First use when you want develop system Developer Environment
  • Second CS use when app publish Publish Environment

For second connection-string must write full path


Code

For get connection String in App.config file, you can use this code

var conStr = ConfigurationManager.ConnectionStrings["DevConnectionString"].ConnectionString;



回答2:


I found that I can not check the version of SQL Server LocalDB installed on a second computer through the Command Prompt using the command sqllocaldb info MSSQLLocalDB (because of an error).

So I decided to recreate the MSSQLLocalDB instance using the following commands:

1) sqllocaldb d MSSQLLocalDB

2) sqllocaldb c MSSQLLocalDB

And after that the program successfully connected to the database.

I hope this information helps someone.



来源:https://stackoverflow.com/questions/62051900/a-network-related-or-instance-specific-error-occurred-while-establishing-a-conne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!