C#数据库连接SQL

C#数据库连接SQL,c#,sqlconnection,local-database,C#,Sqlconnection,Local Database,我正试图使它,使我可以使用该程序,无论我把文件夹,所以它不仅限于在一个特定的地方。 这是我正在使用的连接字符串 string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf; Integrated Security = True";

我正试图使它,使我可以使用该程序,无论我把文件夹,所以它不仅限于在一个特定的地方。 这是我正在使用的连接字符串

string constring = "Data Source = (LocalDB)\\MSSQLLocalDB;
AttachDbFilename = C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf; 
Integrated Security = True";

此连接字符串工作正常,但如上所述,我希望它与我放置它的位置保持一致

您可以为数据源、attachDbFilename等值提供变量,然后在加载事件中检索值。或者使用配置文件检索连接字符串。正如在第一个解决方案中出现的那样

string constring = "Data Source = "+ YourDataSource +"; AttachDbFilename = "+ YourAttachedDBFilePath +"; Integrated Security = True";

您应该将数据库文件放入文件夹app(debug或release)中,并通过
应用程序调用它。如果可能的话,启动路径

,然后将所需的数据库放入AppData文件夹,然后在ConnectionString中使用以下内容

Server=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BarcodeDB.mdf;Database=BarcodeDB;

如果没有,那么最好的方法是使用建议的选项,但是在这种情况下,您必须知道数据库在每个环境中的确切位置,或者在每个环境中进行搜索以找到必要的数据库。

如果您想找到项目的路径,您可以使用:

string path = System.AppDomain.CurrentDomain.BaseDirectory;
另一种选择是,如果您决定将db文件存储在生成文件夹中(在可执行文件旁边):

例如:

// filename of your Db file
string filename = "BarcodeDB.mdf";
// combine filename and your local path
string dbFilePath = Path.Combine(path, filename);
// use the db filepath in your constring using string interpolation
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = {dbFilePath}; Integrated Security = True";

因此,当您移动项目或将其放在各种机器上(假设存在db文件)时,它应该能够找到它。

如何在加载时检索值?您正在创建哪种类型的项目?它根据项目类型而不同。大多数情况下,数据库连接字符串在windows应用程序的app.config文件和web应用程序的web.config文件中定义
// filename of your Db file
string filename = "BarcodeDB.mdf";
// combine filename and your local path
string dbFilePath = Path.Combine(path, filename);
// use the db filepath in your constring using string interpolation
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = {dbFilePath}; Integrated Security = True";