[英]How can I fix a SqlException incorrect syntax error in my code?
This is code that references a SQL Server database to retrieve to information to be put into a DataGridView
.这是引用 SQL Server 数据库以检索要放入DataGridView
。
I get an error:我收到一个错误:
SqlException [incorrect syntax] SqlException [不正确的语法]
Code:代码:
private void DisplayData()
{
adapt = new SqlDataAdapter("SELECT geoCode, cancer2004" +
"FROM Regional_Intel$" +
"WHERE geoCode LIKE '" + txtDMA.Text + "'", con);
// cmd.Parameters.AddWithValue("@dma", txtDMA.Text);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
}
How can I fix it?我该如何解决?
Add spaces in your SQL string.在 SQL 字符串中添加空格。 Also, very bad idea to use string concatenation.此外,使用字符串连接非常糟糕。
Add spaces like this:像这样添加空格:
{
adapt = new SqlDataAdapter("Select geoCode, cancer2004 " +
"FROM Regional_Intel$ " +
"where geoCode LIKE '" + txtDMA.Text + "'", con);
//cmd.Parameters.AddWithValue("@dma", txtDMA.Text);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
}
Use parameters like this:使用这样的参数:
{
adapt = new SqlDataAdapter("Select geoCode, cancer2004 " +
"FROM Regional_Intel$ " +
"where geoCode LIKE @dma", con);
adapt.SelectCommand.Parameters.Add("@dma", SqlDbType.NVarChar).Value = txtDMA.Text;
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
}
Separate out your SQL string:分离出你的 SQL 字符串:
{
var query = @"
SELECT geoCode, cancer2004
FROM Regional_Intel$
WHERE geoCode LIKE @dma";
adapt = new SqlDataAdapter(query, con);
adapt.SelectCommand.Parameters.Add("@dma", SqlDbType.NVarChar).Value = txtDMA.Text;
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.