亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C# Winform SQL Server 連接字符串

C# Winform SQL Server 連接字符串

PHP
慕村9548890 2024-01-20 22:30:34
處理使用 SQL Server 的 WinForm 項目。目前,my 的屬性設置為 。MusicPlayerDB.mdfCopy to Output DirectoryCopy if newer運行我的 后,我關閉了 Winform 并繼續在服務器資源管理器中檢查該表。但似乎我的表沒有更新。但是如果我去檢查和檢查,數據就在那里。InsertIntoDBBin/DebugMusicPlayerDB.mdf解決此問題的最佳方法是什么?我看到其他評論說使用絕對路徑(或類似的東西),但如果可能的話,我想避免這種情況。.mdf這是我的連接字符串,private const String CONNECTION_STRING = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MusicPlayerDB.mdf;Integrated Security=True";這是我的插入代碼:private static void InsertIntoDB(List<string> userAccout) {    String sqlQuery = "INSERT INTO dbo.UserAccount (UserName, UserPassword, PasswordQuestion, PasswordHint, PasswordKey) "                      + "VALUES (@UserName, @UserPassword, @PasswordQuestion, @PasswordHint, @PasswordKey);";    using(SqlConnection connection = new SqlConnection(CONNECTION_STRING))     {        connection.Open();          //open connection        using(SqlCommand command = new SqlCommand(sqlQuery, connection))         {                 // set up command            using(SqlTransaction trans = connection.BeginTransaction())             {                try                 {                    command.Connection = connection;                    command.Transaction = trans;                    command.Parameters.AddWithValue("@UserName", userAccout[0]);                    command.Parameters.AddWithValue("@UserPassword", userAccout[1]);                    command.Parameters.AddWithValue("@PasswordQuestion", userAccout[2]);                    command.Parameters.AddWithValue("@PasswordHint", userAccout[3]);                    command.Parameters.AddWithValue("@PasswordKey", Convert.ToInt32(userAccout[4]));                    int r = command.ExecuteNonQuery();  //execute the command                    trans.Commit();                }                 catch(Exception ex)                 {                    MessageBox.Show(ex.Message);    //couldn't execute command                }            }        }    }} //end of InsertIntoDB
查看完整描述

1 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

這就是它的預期工作方式。|數據目錄|在桌面應用中,指向可執行文件的運行位置。這意味著在 VS 中運行應用時為 bin\debug 或 bin\release(工作文件夾),但在 VS 外部運行應用時為安裝文件夾。

這種安排允許您將空的 MDF 保留在項目文件夾中,而工作副本則保留在輸出文件夾中。當需要更改數據庫架構中的某些內容時,可以使用服務器資源管理器更改項目文件夾中的副本。因此,在下一個 VS 會話開始時,將在輸出文件夾中復制該文件的新副本。當您需要分發應用時,可以在項目文件夾中分發 MDF 文件。

當然,如果需要檢查數據庫的工作副本中發生的情況,則可以在服務器資源管理器中創建指向工作文件夾中的 MDF 文件的新連接。

如果您需要更多控制,則可以更改替換字符串 |數據目錄|點。


查看完整回答
反對 回復 2024-01-20
  • 1 回答
  • 0 關注
  • 263 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號