private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
string strcon = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Fellipe\\documents\\visual studio 2010\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\PUBS.MDF;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=True;User Instance=True";
SqlConnection conexao = new SqlConnection(strcon);
conexao.Open();
SqlDataAdapter Buscar = new SqlDataAdapter("SELECT ROTA, DOCA FROM Planilha4 WHERE D2 =" + monthCalendar1.SelectionStart.ToString("dd/MM/yyyy"), conexao);
DataTable dt = new DataTable();
Buscar.Fill(dt);
SqlDataAdapter sda = new SqlDataAdapter();
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.DataSource = bSource;
sda.Update(dt);
}
错误发生在Buscar.Fill(dt);
我想消除此错误。我等着回复。
感谢
答案 0 :(得分:5)
如果在构建之后查看生成的SQL字符串,您将看到问题所在。日期文字周围没有引号,因此SQL将斜杠视为数学方程式。
您应该查看使用存储过程或参数化SQL字符串来防止此问题。您可以在此站点上搜索“sql注入漏洞”,以查看在SQL中使用参数的大量示例。 Here's a related question.
答案 1 :(得分:2)
您在monthCalendar1.SelectionStart.ToString("dd/MM/yyyy")
之前和之后遗漏了一些“''”。见下文:
SqlDataAdapter Buscar = new SqlDataAdapter("SELECT ROTA, DOCA FROM Planilha4 WHERE D2 = '" + monthCalendar1.SelectionStart.ToString("dd/MM/yyyy") + "'", conexao);
此外,如果您对monthCalendar1
等控件有外部依赖关系,我强烈建议您参数化查询。这是一个简单的例子:
string command = "SELECT ROTA, DOCA FROM Planilha4 WHERE D2 = @mnthCalendar";
sqlDA.SelectCommand.Parameters.Add(@mnthCalendar, SqlDbType.DateTime).Value = monthCalendar1.SelectionStart;