2009/07/02

MySQL Prepare() 使用法 + UTF-8 亂碼解決

MySqlCommand 提供的 Prepare() 可以讓你避免自行組合字串的不便性和 SQL Injection 的防止。前面提到過 21.2.4.6 節有範例可以參考。

MySqlConnection conn = new MySqlConnection("server=localhost;user=root;database=test;port=3306;charset=utf8;");
MySqlCommand cmd = new MySqlCommand("INSERT INTO test VALUES (@ID, @Name)", conn);
cmd.Prepare();
cmd.Parameters.Add("@ID", MySqlDbType.Int16);
cmd.Parameters.Add("@Name", MySqlDbType.String);

for(int i = 6; i < 10; i++){
cmd.Parameters["@ID"].Value = i;
cmd.Parameters["@Name"].Value = "修羅パンツ" + i.ToString();
cmd.ExecuteNonQuery();
}


只要下好 SQL Command 後呼叫 Prepare(),再塞入 Parameters,最後 Execute 就可以完成了。這邊範例是先定義好 Parameters 的型態 (ID 是整數、Name 是字串)後,利用迴圈批次新增資料 (Parameters["@ID"].Value) 再呼叫 ExecuteNonQuery 新增,就可以達成重複使用。

另外,如果在 Connection String 時沒有設定 charset=utf8 (注意是 utf8 不是 utf-8!),寫入時會預設使用 iso-8859-1 (Latin1) 來寫入,非英數字就會變成 ???。另外新增 MySQL 資料表時,Table 跟每個欄位也要設定使用 utf8 (utf8_general_ci) 這樣讀寫才會正常。

總結,要排除亂碼,在 MySQL 資料表要設定為 utf8 外,程式建立連線時也要明顯定義 charset=utf8 才可以。

沒有留言:

張貼留言