【问题标题】:What is the datatype for Date in SQL Server?SQL Server 中日期的数据类型是什么?
【发布时间】:2021-01-18 00:20:12
【问题描述】:

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

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;
}

【问题讨论】:

  • 无论如何,你不应该将值直接连接到查询中,这会导致 SQL 注入的阴暗面
  • 这能回答你的问题吗? Pass parameters correctly to SqlCommand
  • 考虑如果有人在 txtReason 中输入 ',0); DROP DATABASE MyDb; SELECT (' 会发生什么
  • 在进一步询问之前您需要解决的代码问题:1.insert 语句中指定要插入的列名2. b> 参数化查询,传递具有正确数据类型的参数和字符串长度 3. 将值转换为这些参数类型4. 处理连接和命令与using 块。不要缓存它们
  • 这绝对是将数据组合到查询中的错误方式(并且已经持续了很长时间),如果您实际上正在使用,则将 DTP 值转换为错误的字符串数据库中的日期列。

标签: c# .net sql-server


【解决方案1】:

请贴出reportinfo的表结构

正如@Squirrel 所述,列不匹配。您正在尝试插入 5 列:

txtDriverName.Text + "','" + txtLPNO.Text + "','" + txtCODENO.Text + "''" + txtReason.Text + "','" + dateTimePicker1.Value.ToString()

但显然表中的列数与此不符。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-06
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2014-10-20
    • 1970-01-01
    相关资源
    最近更新 更多