带有本地 .mdf 数据库的 VB.Net ConnectionString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22680515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:13:48  来源:igfitidea点击:

VB.Net ConnectionString with a local .mdf database

sql-servervb.netconnection-string

提问by eirishainjel

I am publishing a project application and I think having a connectionstring with this format

我正在发布一个项目应用程序,我认为有一个这种格式的连接字符串

cn.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\iaprubillos\My Documents\PROJECT\myProject\database\myDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

is not a friendly and definitely won't work when I will run the application on other computers. Question: Can I use a connectionstring in a format of

不友好,当我在其他计算机上运行该应用程序时肯定不会工作。问题:我可以使用以下格式的连接字符串吗?

cn.ConnectionString = "Data Source=|DataDirectory|\myDatabase.mdf"

and store the database in bin folder so that when I Build my project and compile to an .exe file, the .exe file can still access the database?

并将数据库存储在bin文件夹中,以便当我构建我的项目并编译为.exe文件时,.exe文件仍然可以访问数据库?

回答by Matt Wilko

You can use My.Application.Info.DirectoryPathto get the path where your application is running from. So you can modify your connextion string code like this:

您可以使用My.Application.Info.DirectoryPath来获取应用程序运行所在的路径。所以你可以像这样修改你的连接字符串代码:

cn.ConnectionString = String.format("Data Source=.\SQLEXPRESS;AttachDbFilename={0}\myDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True", My.Application.Info.DirectoryPath)