我想在我的SQLite数据库中插入一个Date,DateTime(无秒)和Time。我可以插入数据,但信息有误。保存数据的变量是正确的,但是将数据插入数据库时,信息是错误的。
我有这张桌子:
[Table(“ tblCaf”)]
公共类CAFTable
{
[PrimaryKey,MaxLength(100)]
公共字符串CAFNo {get;组; }
public int EmployeeID {get;组; }
公共DateTime CAFDate {get;组; }
[MaxLength(100)]
公用字符串CustomerID {get;组; }
公开的DateTime StartTime {组; }
公共DateTime EndTime {get;组; }
公共字符串Photo1 {get;组; }
公共字符串Photo2 {get;组; }
公共字符串Photo3 {get;组; }
公用字符串MobilePhoto1 {get;组; }
公共字符串MobilePhoto2 {组; }
公共字符串MobilePhoto3 {get;组; }
[MaxLength(1000)]
公共字符串备注{get;组; }
[MaxLength(1000)]
公共字符串OtherConcern {组; }
公共DateTime LastSync {get;组; }
公共DateTime ServerUpdate {组; }
公开的DateTime MobileUpdate {组; }
}
这是我的代码:
var caf = entCafNo.Text;
var retailerCode = entRetailerCode.Text;
var employeeNumber = entEmployeeNumber.Text;
var date = dpDate.Date; //I get the date inside the datepicker
var startTime = tpTime.Time; //I get the time inside the time picker
var endTime = DateTime.Now.TimeOfDay; //I get the current time
var photo1url = entPhoto1Url.Text;
var photo2url = entPhoto2Url.Text;
var photo3url = entPhoto3Url.Text;
var otherconcern = entOthers.Text;
var remarks = entRemarks.Text;
var current_datetime = DateTime.Now.ToString("yyyy-MM-dd hh:mm"); //I get the current datetime
string caf_sql = "INSERT INTO tblCaf(CAFNo, EmployeeID, CafDate, CustomerID, StartTime, EndTime, Photo1, Photo2, Photo3, Remarks, OtherConcern, LastSync, MobileUpdate)
VALUES('" + caf + "','" + employeeNumber + "', '" + date + "', '" + retailerCode + "', '" + startTime + "', '" + endTime + "', '" + photo1url + "', '" + photo2url + "', '" + photo3url + "', '" + remarks + "', '" + otherconcern + "', '" + current_datetime + "', '" + current_datetime + "')";
await conn.ExecuteAsync(caf_sql);
我可以获得正确的日期,时间和日期时间。问题是当我保存此日期时,日期变为01/01/0001,时间变为00:00:00,日期时间变为01/01/0001 00:00:00,换句话说,数据未正确添加。我可以改善我的代码吗?
答案 0 :(得分:2)
与其手动构建一个插入语句,不如通过使用Insert函数获得更好的结果
var item = new CAFTable {
CAFDate = dpDate.Date,
StartTime = tpTime.Date, // note Time is a TimeSpan, not a DateTime
EndTime = DateTime.Now, // note TimeOFDay is a TimeSpan, not a DateTime
LastSync = DateTime.Now,
MobileUpdate = DateTime.Now
... set any other properties as needed
};
await conn.InsertAsync(item);