如下所示,我声明了应用程序所需的查询和数据库操作。在本课程中,我尝试使用TimeSpan
计算总时间,但未成功。
public class Operations
{
public Dbconection db = new Dbconection();
public Informations info = new Informations();
DateTime Vrijeme;
DateTime myDate1;
public int insertEmp(Informations info)
{
DateTime Time = DateTime.Now;
DateTime myDate1 = new DateTime(Time.Year, Time.Month,
Time.Day, Time.Hour, 10, 00);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO empRegister" +
"(Operater,Artikl,Kal,Bazz,Tempa,Time,Status)" +
"VALUES ('" + info.operater + "','" + info.artikl + "','" + info.kal + "','" + info.bazz + "','" + info.tempa + "', @time, 'online')";
cmd.Parameters.AddWithValue("@time", myDate1);
return db.ExeNonQuery(cmd);
}
public DataTable Logout1(Informations info)
{
DateTime Logout = DateTime.Now;
DateTime myDate2 = new DateTime(Logout.Year, Logout.Month, Logout.Day, Logout.Hour, 30, 00);
TimeSpan ts = myDate2.Subtract(myDate1);
TimeSpan result = new TimeSpan(ts.Hours, ts.Minutes, ts.Milliseconds);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update empRegister set Logout = @logout, Total = @THETIME, Status = 'logout' where Operater ='" + info.operater + "' and Status = 'online'";
cmd.Parameters.AddWithValue("@logout", myDate2);
cmd.Parameters.AddWithValue("@THETIME", SqlDbType.Time);
cmd.Parameters["@THETIME"].Value = result;
return db.ExeReader(cmd);
}
}
使用插入按钮我希望使用Datetime.Now
并使用更新按钮我想存储两个DateTime
与Timespan
的当前时间和总时间。我正在使用SQL DB。
答案 0 :(得分:0)
我不是存储时间数据的忠实粉丝。但是,您可以在SQL查询中执行此操作,假设您将其存储为时间列:
cmd.CommandText = "update empRegister set Logout = @logout, Total = CONVERT(time(7),DATEADD(SECOND,
DATEDIFF(SECOND, Time, @logout),
0)), Status = 'logout' where Operater = @Operater and Status = 'online'";
cmd.Parameters.AddWithValue("@logout", myDate2);
cmd.Parameters.AddWithValue("@Operater", info.operater);
没有必要使用TimeSpan代码。
另外,我将操作符作为参数。它在您的问题和我的查询中拼写错误。
这是一个时间列使用的SQL小提琴示例:
create table y
(
x time
);
INSERT INTO Y SELECT
CONVERT(time(7),DATEADD(SECOND,
DATEDIFF(SECOND, GETDATE()-7.5, GETDATE()),
0));
SELECT * FROM Y
请注意,时间栏限制为24小时。
答案 1 :(得分:0)
在empRegister表中,我存储了3个数据类型,其中包含名称(Time,Logout和Total)。我不知道我哪里错了,欢迎一切帮助。