C# SQL Server中日期的数据类型是什么?

C# SQL Server中日期的数据类型是什么?,c#,.net,sql-server,C#,.net,Sql Server,我在尝试使用DateTimePicker将当前日期和时间插入表时遇到此错误。我尝试在SQL Server中使用Date和datetime数据类型,但似乎无法修复此错误 private void btnReport_Click(object sender, EventArgs e) { if (isFormValid()) { DialogResult dialog = MessageBox.Show("Are You Sure Y

我在尝试使用DateTimePicker将当前日期和时间插入表时遇到此错误。我尝试在SQL Server中使用
Date
datetime
数据类型,但似乎无法修复此错误

private void btnReport_Click(object sender, EventArgs e)
{
        if (isFormValid())
        {
            DialogResult dialog = MessageBox.Show("Are You Sure You Want To Report this Driver?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dialog == DialogResult.Yes)
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("insert into reportinfo values('" + txtDriverName.Text + "','" + txtLPNO.Text + "','" + txtCODENO.Text + "''" + txtReason.Text + "','" + dateTimePicker1.Value.ToString()+ "');", sqlCon);

                    int temp = cmd.ExecuteNonQuery();

                    if (temp > 0)
                    {
                       MessageBox.Show("Cab Driver Successfully Reported", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Couldn't Report Driver Please Check the current fields", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error inserting data" + ex, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                txtDriverName.Clear();
                txtLPNO.Clear();
                txtCODENO.Clear();

                this.OnLoad(e);
            }
        }
    }

    private bool isFormValid()
    {
        if (txtDriverName.Text.Trim() == string.Empty || txtLPNO.Text.Trim() == string.Empty)
        {
            MessageBox.Show("Please Fill All Required Fields", "Required Fields are Empty",  MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
        else
            return true;
}


请发布
reportinfo

正如@Squirrel所提到的,列不存在;不匹配。您正在尝试插入5列:

txtDriverName.Text + "','" + txtLPNO.Text + "','" + txtCODENO.Text + "''" + txtReason.Text + "','" + dateTimePicker1.Value.ToString()
但表中的列数显然与此不匹配


同样如前所述,您需要参数化查询以避免SQL注入。

不管是什么,您不应该将值直接连接到查询中,这会导致SQL注入的黑暗面。这是否回答了您的问题?想想如果有人进入<代码>,会发生什么,0);删除数据库MyDb;挑选(“插入txtreason”在进一步询问之前,您需要对代码中的问题进行排序:1.在
insert
语句中指定要插入的列名2.参数化查询,为字符串传递具有正确数据类型和长度的参数3.将值强制转换为这些参数类型4.使用
usi处理连接和命令ng
块。不要缓存它们。这绝对是将数据组合到查询中的错误方式(这种方式已经很长时间了)。此外,如果您实际上在数据库中使用了日期列,则将DTP值转换为字符串是错误的。