我希望用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' 并提前感谢你。
答案 0 :(得分:2)
假设您的字段是数据库中的DateTime类型,您可以执行以下操作。它只是在表you should always use parameter in SQL中插入日期。
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", DateTime.Parse(dateTimePicker1.Value.Date.ToShortDateString()));
cmd.ExecuteNonQuery();
答案 1 :(得分:0)
使用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);