1

我希望用 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);

但是数据库中的字段始终填充默认值:01/01/1900 00:00:00,当我使用断点检查其值时,它做得很好,例如今天它的值是'22/04/ 2012' 提前谢谢你。

4

2 回答 2

2

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

SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", DateTime.Parse(dateTimePicker1.Value.Date.ToShortDateString()));
cmd.ExecuteNonQuery();
于 2012-04-22T14:35:48.857 回答
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);
于 2012-04-22T14:35:23.040 回答