處理使用 SQL Server 的 WinForm 項目。目前,my 的屬性設(shè)置為 。MusicPlayerDB.mdfCopy to Output DirectoryCopy if newer運行我的 后,我關(guān)閉了 Winform 并繼續(xù)在服務(wù)器資源管理器中檢查該表。但似乎我的表沒有更新。但是如果我去檢查和檢查,數(shù)據(jù)就在那里。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條經(jīng)驗 獲得超7個贊
這就是它的預(yù)期工作方式。|數(shù)據(jù)目錄|在桌面應(yīng)用中,指向可執(zhí)行文件的運行位置。這意味著在 VS 中運行應(yīng)用時為 bin\debug 或 bin\release(工作文件夾),但在 VS 外部運行應(yīng)用時為安裝文件夾。
這種安排允許您將空的 MDF 保留在項目文件夾中,而工作副本則保留在輸出文件夾中。當(dāng)需要更改數(shù)據(jù)庫架構(gòu)中的某些內(nèi)容時,可以使用服務(wù)器資源管理器更改項目文件夾中的副本。因此,在下一個 VS 會話開始時,將在輸出文件夾中復(fù)制該文件的新副本。當(dāng)您需要分發(fā)應(yīng)用時,可以在項目文件夾中分發(fā) MDF 文件。
當(dāng)然,如果需要檢查數(shù)據(jù)庫的工作副本中發(fā)生的情況,則可以在服務(wù)器資源管理器中創(chuàng)建指向工作文件夾中的 MDF 文件的新連接。
如果您需要更多控制,則可以更改替換字符串 |數(shù)據(jù)目錄|點。
- 1 回答
- 0 關(guān)注
- 333 瀏覽
添加回答
舉報
0/150
提交
取消