2017-10-19 120 views
-1

我試圖讓它可以使用程序,我把文件夾放在哪裏,因此它不僅限於在一個特定的地方。 這是我現在使用的連接字符串C#數據庫連接SQL

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

此連接字符串工作正常,所有,但上面說的,我想這是對環境的我把它

回答

0

可以提供變量值,例如數據源,attachDbFilename等。然後在加載事件中檢索值。或者使用配置文件來檢索連接字符串。作爲第一個解決方案出現這樣

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

我如何檢索加載時的值? –

+0

您正在創建哪種類型的項目?根據項目類型不同而不同。大多數情況下,數據庫連接字符串在Windows應用程序的app.config文件和Web應用程序的web.config文件中定義 –

0

你應該把數據庫文件夾的應用程序(調試或發佈)中,並用Application.StartupPath

0

如果可以調用它,然後把所需要的數據庫到應用程序數據文件夾然後用在ConnectionString以下

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

如果不是,那麼做它使用提出百路達的選項,但在這種情況下,最好的辦法,你必須知道電子在每個單一環境中的數據庫的xact位置,或者在每個環境中進行搜索以找到必要的DB。

0

如果你想找到你的項目的路徑,你可以使用:

string path = System.AppDomain.CurrentDomain.BaseDirectory; 

的選擇,如果你決定(旁邊的可執行文件)存儲在構建文件夾中的數據庫文件:

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"; 

所以,當你移動你的項目或有它在不同的機器(假設分貝文件存在),它應該能夠找到它。