2008年12月30日 星期二

[SQLite]新增資料至Boolean欄位發生錯誤!

今天新增一筆資料時出現錯誤
SQLite error
no such column: True

更正來源︰http://chriscraig.net/blog/sqlite-boolean-true-or-false/
INSERT INTO myTable (boolField) VALUES(true); (Failed)

INSERT INTO myTable (boolField) VALUES('true'); (Successed)

[SQLite]字串未被辨認為有效的 DateTime?

明明只是從 資料庫 Select 資料出來而已,尚未作任何的資料處理。
為何會出現 Exception 呢?
public void SelectTable()
{
 string strCommand = "SELECT * FROM Table1";
 SQLiteConnection myConnection = new SQLiteConnection(strConnection);
 SQLiteCommand myCommand = new SQLiteCommand(strCommand, myConnection);
 
 DataTable table = new DataTable();
 try
 {
  myConnecion.Open();
  table.Load(myCommand.ExecuteReader()); //在這行跳出 Exception
 }
 catch(Exception ex){ throw new Exception(ex.Message); }
 finally{ myConnection.Close();}
}
這沒可能啊!! command如此的單純,怎麼還會出錯呢?
trace code 後發現原因出在 table裡面的內容錯誤!!
不會吧 怎麼會有 Insert 成功 Select 失敗的事呢?
我也不知道 實在是苦惱啊!

以下是原來 Insert 一筆資料的方法︰
public void InsertData()
{
 string strCommand = "INSERT Table1(Start_Time) VALUES('2008/12/30 23:59:59')";
 SQLiteConnection myConnection = new SQLiteConnection(strConnection);
 SQLiteCommand myCommand = new SQLiteCommand(strCommand, myConnection);
 
 try
 {
  myConnecion.Open();
  int count = myCommand.ExecuteNonQuery(); //count 為1表示資料新增成功
 }
 catch(Exception ex) { throw new Exception(ex.Message); }
 finally { myConnection.Close();}
}
可是用上面的寫法,雖然可以新增成功,但資料會讀不出來!!
(原本使用於MySQL上面讀寫皆正常)

下面用Parameter的方式改寫︰
public void InsertData()
{
 string strCommand = "INSERT Table1(Start_Time) VALUES(@parStart_Time)";
 SQLiteConnection myConnection = new SQLiteConnection(strConnection);
 SQLiteCommand myCommand = new SQLiteCommand(strCommand, myConnection);
 DateTime sTime = new DateTime(2008, 12, 30, 23, 59, 59);
 myCommand.Parameter.Add(new Parameter("@parStart_Time", sTime);
 try
 {
  myConnecion.Open();
  int count = myCommand.ExecuteNonQuery(); //count 為1表示資料新增成功
 }
 catch(Exception ex) { throw new Exception(ex.Message); }
 finally { myConnection.Close();}
}
ok 現在讀寫都正常了(使用MySQL時必須將符號換成符號)

結論︰沒事還是使用Parameter帶值吧! 既方便又安全,別再用 + 號了

2008年12月24日 星期三

[SQLite]列出資料庫中的所有資料表

DataTable ListAllTables(string filePath, string userID, string psw)
{
 string strConnection = string.Format("Data source={0}", filePath);
 SQLiteConnection myConnection = new SQLiteConnection(strConnection);
 SQLiteCommand myCommand = new SQLiteCommand(myConnection);
 myCommand.CommandText = "SELECT * FROM sqlite_master WHERE type='table'";
 try
 {
  myConnection.Open();
  DataTable table = new DataTable();
  table.Load(myCommand.ExecuteReader());
  return table;
 }
 catch { return null; }
 finally { myConnection.Close(); }
}

2008年12月11日 星期四

控制項跨執行緒無效

//只要加上這一行,就能不檢查執行緒衝突
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;