2012-06-05 103 views
1

可能重复:
SQL Express Connection string - Relative to application location相对路径连接字符串vb.net

我已经写在vb.net中的桌面应用程序。该应用程序使用SQL Server Express 2008数据库(.mdf文件)。 目前,我有连接字符串绝对路径是这样的:

Dim ObjConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Pantheo\Documents\Visual Studio 2010\Projects\Food Manager 2012(new)\Food Manager 2012\Food_CustomerDB.mdf;Integrated Security=True;User Instance=True") 

在我的电脑运行好了。如果我建立它,并得到.exe运行到不同的电脑它崩溃,因为它不能附加数据库。

我已经尝试过了相对使用此连接字符串,使:

Dim ObjConnection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Food_CustomerDB.mdf;Initial Catalog=Food_CustomerDB;Integrated Security=True;User Instance=True") 

没有成功。有人能帮我吗?我知道有很多其他的答案,基本上关于C#,但我无法实现它们。在此先感谢

+0

http://stackoverflow.com/questions/3500829/sql-express-connection-string-relative-to-application-location可能是你想要的,那里有很少的代码,不会轻易地转换为vb –

回答

1

DataDirectory值只是从AppDomain.CurrentDomain属性列表中提取的字符串。在WinForm应用程序中没有预先定义,但可以在打开数据库之前对其进行设置。

AppDomain.CurrentDomain.SetData("DataDirectory", @"C:\MyReadWriteFolder") 

则连接字符串AttachDbFilename=|DataDirectory|\Food_CustomerDB.mdf作品应该提供你把数据库有(C:\ MyReadWriteFolder)。

+0

而且我如何把数据库放在另一台机器上?用安装程序mabey? – Pantheo

+0

当然,您需要安装工具,从Visual Studio的deplyment项目开始,或者使用许多免费或付费工具中的一种。请记住,还需要在客户PC上安装SQL Server。或者,如果您的程序是针对单个用户的,您可以使用SqlServer的[LocalDB](http://stackoverflow.com/questions/9655362/localdb-deployment-on-client-pc)版本 – Steve

+0

谢谢Steve。我去做。 – Pantheo