[英]C# database connection SQL
我正在尝试制作它,以便我可以在我放置文件夹的任何地方使用该程序,因此它不仅限于在一个特定的地方。 这是我现在使用的连接字符串
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(调试或发布)中并通过Application.StartupPath
调用它
如果可能,则将所需的数据库放入 AppData 文件夹中,然后在 ConnectionString 中使用以下内容
Server=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BarcodeDB.mdf;Database=BarcodeDB;
如果没有,那么最好的方法是使用提议的选项Promod ,但在这种情况下,您必须知道数据库在每个环境中的确切位置,或者在每个环境中进行搜索以找到必要的数据库。
如果要查找项目的路径,可以使用:
string path = System.AppDomain.CurrentDomain.BaseDirectory;
另一种选择,如果您决定将 db 文件存储在构建文件夹中(在您的可执行文件旁边):
string path = Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
例子:
// 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 文件),它应该能够找到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.