作者mosluce ()
看板C_Sharp
標題[問題] DataSet、DataTableAdapter 回存資料庫
時間Thu Nov 18 10:46:56 2010
開發環境:C# 2010
資料庫:SQLite (SQLite.Net)
問題在製作可增、刪、改的DataGridView遇到
以下次程式碼片段
宣告&初始
SQLiteConnectionStringBuilder connBuilder;
SQLiteConnection conn;
SQLiteDataAdapter adapter;
DataSet ds;
private void SettingUserManage_Load(object sender, EventArgs e)
{
SQLiteCommand cmd = new SQLiteCommand();
ds = new DataSet();
connBuilder = new SQLiteConnectionStringBuilder();
connBuilder.DataSource = "Data/database.db3";
conn = new SQLiteConnection(connBuilder.ToString());
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Users";
cmd.CommandType = CommandType.Text;
adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(ds, "Users");
usersGridView.DataSource = ds.Tables["Users"];
}
問題
private void userGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{/*當編輯結束時*/
SQLiteCommand cmd = new SQLiteCommand();
/*取得編輯資料行*/
DataGridViewRow row = usersGridView.Rows[e.RowIndex];
string uid = row.Cells["UserID"].Value.ToString();
string pass = row.Cells["Password"].Value.ToString();
string name = row.Cells["UserCName"].Value.ToString();
bool admin = (bool)row.Cells["IsAdmin"].Value;
/*以下試圖使用Adapter的Update功能才回存*/
/*註解部分為成功的方法1*/
/*根據查詢到的資料實作方法2,無法寫回資料庫*/
//conn.Open(); //--方法1
cmd.Connection = conn;
cmd.CommandText = String.Format("UPDATE Users SET Password='{0}', UserCName='{1}', IsAdmin='{2}' WHERE UserID='{3}'", pass, name, admin, uid);
//cmd.ExecuteNonQuery(); //--方法1
//conn.Close(); //--方法1
//MessageBox.Show(adapter.AcceptChangesDuringUpdate.ToString());
adapter.UpdateCommand = cmd; //--方法2
adapter.Update(ds.Tables["Users"]); //--方法2
ds.AcceptChanges(); //--方法2
}
麻煩高手解惑~THANKS MUCH MUCH
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.85.58.90
※ 編輯: mosluce 來自: 219.85.58.90 (11/18 10:55)
推 horngsh:你有把Users資料表建立主鍵嗎? 11/18 12:23
推 Deadshot465:你的DataAdapter與DataSet的用法可能不太對 11/18 12:24
→ Deadshot465:UpdateCommand似乎要用參數來設定 並且參數值要是 11/18 12:25
→ Deadshot465:資料行的名稱 此外你取得的更新資料好像也沒先寫入 11/18 12:26
→ Deadshot465:ds.Tables["Users"]中 11/18 12:27
→ mosluce:回horngsh:有建立 primary key 11/18 13:04
→ mosluce:@Deadshot:研究一下^^,感謝提供資料~ 11/18 13:05
推 horngsh:樓主,D大說得是對的. 11/18 14:17
→ mosluce:SQLite.NET 用法上似乎不太一樣... 繼續研究 11/18 16:20