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