开发者

Dynamically sql connection

hi i`m using visual basic express 2010 and SQL server 2008 R2 this is my problem i create database in sql, then i connect to database by visual basic. like

<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections></configSections> <connectionStrings> <add name="WindowsApplication1.My.MySettings.BPdataConnectionString" connectionString="Data Source=.\SQLBAC;AttachDbFilename=G:\SQLSERVER\MSSQL10_50.SQLBAC\MSSQL\DATA\BPdata.mdf;Persist Security Info=True;User ID=sa;Password=martin;Connect Timeout=30;User Instance=False" providerName="System.Data.SqlClient" /> <add name="BPdataEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLBAC;AttachDbFilename=G:\SQLSERVER\MSSQL10_50.SQLBAC\MSSQL\DATA\BPdata.mdf;Persist Security Info=True;User ID=sa;Password=martin;Connect Timeout=30;User Instance=False;MultipleActiveResultSets=True&quot;" providerName="System.Da开发者_高级运维ta.EntityClient" />

everything is working but if i will use it in other PC then database directory and SQL server name will be different... so i need to ask program before start for server name, database name...


If you don't know the path of the database file(s), then you will need to ask the user. If you are creating the database file yourself, then you should know the location. If SQL Server is running locally, then you can use . for the source and that will resolve to the local machine.

One thing you can do in AttachDbFilename is start start off with |DataDirectory| (i.e. AttachDbFilename=|DataDirectory|\Folder1\MyDatabase.mdf) and that will resolve to the data directory of your application; with most winforms application, this is the folder that the executable is in, but some technologies (like ClickOnce) will have the data directory located elsewhere.

HTH

EDIT:

If it turns out you do need to build the connection string at runtime, there are classes in the framework that will help with that. The SQL Server version is described here at MSDN: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜