C# 使用01/01/1900 00:00:00插入smalldatetime字段数据库

C# 使用01/01/1900 00:00:00插入smalldatetime字段数据库,c#,datetimepicker,C#,Datetimepicker,我希望用c#插入smalldatetime(DB)字段值,我使用了以下代码 dataAdapter.InsertCommand = new SqlCommand("INSERT INTO journal_jour (id_emp, date, montant_acompte, heur_travaille, Absence) VALUES (" + comboBox1.SelectedValue + "," + dateTimePicker1.Value.Date.ToShort

我希望用c#插入smalldatetime(DB)字段值,我使用了以下代码

 dataAdapter.InsertCommand = new SqlCommand("INSERT INTO journal_jour (id_emp, date, montant_acompte, heur_travaille, Absence) VALUES        (" + comboBox1.SelectedValue + "," + dateTimePicker1.Value.Date.ToShortDateString() + "," + textBox2.Text.Trim() + "," + textBox1.Text.Trim() + "," + ch + ")"
        , con);
但是DB中的字段总是用默认值填充:01/01/1900 00:00:00,当我使用breackpoint检查它的值时,它做得很好,例如今天它的值是'22/04/2012'
并提前感谢您。

使用SqlParameters。您将获得两个结果。
-防止SQL注入攻击
-无需担心每种数据类型的分隔符

string queryText = "INSERT INTO journal_jour " +    
                   "(id_emp, date, montant_acompte, heur_travaille, Absence) " +   
                   "VALUES (@id_emp, @dtValue, @montant, @heur,@absence)";   

dataAdapter.InsertCommand = new SqlCommand(queryText, con);
dataAdapter.InsertCommand.Parameters.AddWithValue("@id_emp",comboBox1.SelectedValue);
dataAdapter.InsertCommand.Parameters.AddWithValue("@dtValue",dateTimePicker1.Value.Date);
dataAdapter.InsertCommand.Parameters.AddWithValue("@montant",textBox2.Text.Trim());
dataAdapter.InsertCommand.Parameters.AddWithValue("@heur",textBox1.Text.Trim());
dataAdapter.InsertCommand.Parameters.AddWithValue("@absence",ch);

假设您的字段在数据库中是DateTime类型,您可以执行以下操作。它仅用于在表中插入日期

SqlCommand cmd=newsqlcommand(“插入()值(@value)”,连接);
cmd.Parameters.AddWithValue(“@value”,DateTime.Parse(dateTimePicker1.value.Date.ToShortDateString());
cmd.ExecuteNonQuery();

尝试将数据库中的数据类型更改为datatime。问题解决后,我在date dataAdapter.InsertCommand=new SqlCommand的值中添加了“”(“插入日记(id、emp、date、montant、acompte、heur、travaille、缺勤)”值(“+comboBox1.SelectedValue+”,”+dateTimePicker1.Value.Date.ToSortDateString()+“,“+textBox2.Text.Trim()+”,“+textBox1.Text.Trim()+”,“+ch+”,con)@用户1348165,哦,是的。但是选择参数化的query@user1348165此外,我还经常使用参数。很好地解释了,我应该学习ORM技术来处理sql的这个问题
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", DateTime.Parse(dateTimePicker1.Value.Date.ToShortDateString()));
cmd.ExecuteNonQuery();