using (var cn = new OracleConnection(csOra))
{
cn.Open();
cn.Execute("TRUNCATE TABLE JEFFTEST");
var idx = 1;
var dttm = DateTime.Now;
var timeStr = dttm.ToString("yyyy/MM/dd HH:mm:ss");
//將DateTime.Now寫入資料庫
cn.Execute("INSERT INTO JEFFTEST (IDX,DTTM) VALUES (:idx, :dttm)", new { idx, dttm });
//從資料庫取出剛才存入的日期備用
var dttmInDb = cn.Query<DateTime>("SELECT DTTM FROM JEFFTEST WHERE IDX=1").Single();
//重新用DateTime.Now當WHERE條件比對,筆數為0
var cnt = cn.Query("SELECT * FROM JEFFTEST WHERE DTTM = :dttm", new { dttm }).Count();
Console.WriteLine($"使用原值WHERE比對 Count={cnt}");
//原因是Oracle DATE型別不包含毫秒
Console.WriteLine($"DB {dttmInDb:HH:mm:ss.fff} vs C# {dttm:HH:mm:ss.fff}");
//把毫秒刪除試試
var dttm2 = dttm.AddMilliseconds(-dttm.Millisecond);
cnt = cn.Query("SELECT * FROM JEFFTEST WHERE DTTM = :dttm2", new { dttm2 }).Count();
//登楞!筆數還是0
Console.WriteLine($"AddMilliseconds修正後比對 Count={cnt}");
//換個方法,先轉字串再ParseExact轉回日期
var dttm3 = DateTime.ParseExact(timeStr, "yyyy/MM/dd HH:mm:ss", null);
cnt = cn.Query("SELECT * FROM JEFFTEST WHERE DTTM = :dttm3", new { dttm3 }).Count();
Console.WriteLine($"ToString+ParseExact轉換後比對 Count={cnt}");
//暗!這樣就找到得,為什麼?兩個時間看起來一樣,但CompareTo不同
Console.WriteLine($"兩種修正結果看似相同 dttm2={dttm2:HH:mm:ss.fff} vs dttm3={dttm3:HH:mm:ss.fff}");
Console.WriteLine($"dttm2.CompareTo(dttm3)={dttm2.CompareTo(dttm3)}");
//問題出在Ticks,二者Ticks不同
Console.WriteLine($"關鍵在ms以下部分:dttm2={dttm2:HH:mm:ss.fffffff} dttm3={dttm3:HH:mm:ss.fffffff}");
//REF: http://stackoverflow.com/a/153014/4335757
dttm2 = dttm.Trim(TimeSpan.TicksPerSecond);
cnt = cn.Query("SELECT * FROM JEFFTEST WHERE DTTM = :dttm2", new { dttm2 }).Count();
Console.WriteLine($"Trim()取到秒再比對 Count={cnt}");
Console.Read();
}