我有一个访问数据库,存储每个员工上班的时间和员工离开的时间。我想计算用户花在工作上的时间。这是我的代码:
DataTable dm = new DataTable();
today = DateTime.Today;
hooodorDa = new OleDbDataAdapter("select heUsers,heCome,heGo from HoodoorEnseraf where heDate=#" + today.ToString("yyyy/MM/dd") + "# and heUsers='" + heUsers.Text + "' ", connection);
hooodorDa.Fill(dm);
DateTime hec = Convert.ToDateTime(dm.Rows[0]["heCome"]);
DateTime heg = Convert.ToDateTime(dm.Rows[0]["heGo"]);
TimeSpan diff = hec - heg;
command = new OleDbCommand("update HoodoorEnseraf set heDifference=? where heUsers=? ;", connection);
command.Parameters.AddWithValue("?", diff);
command.Parameters.AddWithValue("?", heUsers.Text);
我需要在数字字段中插入值,如下面的屏幕截图所示,但我的代码给了我一个错误:
对象无法从dbnull转换为其他类型
我的代码出了什么问题?
答案 0 :(得分:0)
您好像正在寻找TimeSpan.TotalMinutes
财产。您的heDifference
是一个数字,因此您可以获得用户工作的总分钟数并将其存储在那里。
您可以使用TimeSpan.TotalHours
,但分钟更准确。
更正代码:
DataTable dm = new DataTable();
today = DateTime.Today;
hooodorDa = new OleDbDataAdapter("select heUsers,heCome,heGo from HoodoorEnseraf where heDate=#" + today.ToString("yyyy/MM/dd") + "# and heUsers='" + heUsers.Text + "' ", connection);
hooodorDa.Fill(dm);
DateTime hec = dm.Rows[0].Field<DateTime>("heCome");
DateTime heg = dm.Rows[0].Field<DateTime>("heGo");
TimeSpan diff = hec - heg;
command = new OleDbCommand("update HoodoorEnseraf set heDifference=" +
diff.TotalMinutes.ToString() + " where heUsers='" + heUsers.Text + "';", connection);