我正在制作考勤系统而且我不知道如何在数据库中存储日期时间。我真的需要一些帮助我的系统如果有人有任何考勤代码请分享你的代码一点帮助会做的谢谢..
这是我的代码:
con = newSqlConnection(@"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
dt = new DataTable();
cmd = new SqlCommand(@"SELECT EmpID FROM data WHERE EmpID='" + Code.Text + "'", con);
con.Open();
sdr = cmd.ExecuteReader();
int count = 0;
while (sdr.Read())
{
count = count + 1;
}
con.Close();
if (count == 1)
{
con.Open();
DateTime dtn = DateTime.Now;
dtn = Convert.ToDateTime(DateTime.Now.ToString("hh:mm"));
string query = @"INSERT INTO Time (TimeIn) Values ('" + dtn + "')";
cmdd = new SqlCommand(query, con);
sdr = cmdd.ExecuteReader();
sdr.Read();
dataGridView.DataSource = databaseDataSet.Time ;
con.Close();
MessageBox.Show("Verify Ok");
}
else
{
MessageBox.Show("Please Try Again");
}
答案 0 :(得分:2)
请勿使用ExecuteReader()
,ExecuteNonQuery()
;添加查询参数,不要修改查询文本,从技术上讲它可能是这样的:
...
if (count == 1) {
...
DateTime dtn = DateTime.Now;
string query =
@"insert into Time (
TimeIn)
values (
@TimeIn)"; // <- query parameter instead of query text modification
using (var query = new SqlCommand(query, con)) {
// bind query parameter with its actual value
query.Parameters.AddWithValue("@TimeIn", dtn);
// Just execute query, no reader
query.ExecuteNonQuery();
}
...
但是,问题中显示的表Time
看起来很奇怪,几乎不包含TimeIn
字段。