首页 > 解决方案 > System.Data.SqlClient.SqlException:''=' 附近的语法不正确。' 关于数据表和对象

问题描述

我在这个网站和其他地方看过很多类似的问题,但没有一个对我有帮助。

我正在尝试通过查询建立数据库连接,但出现错误

System.Data.SqlClient.SqlException:''=' 附近的语法不正确。'

在 2 行不同的代码上。我尝试在 = 周围的查询中使用空格,但这无济于事。

代码 1 是:

string connectieString = dbConnection();

SqlConnection connection = new SqlConnection(connectieString);

SqlCommand select = new SqlCommand();
select.Connection = connection;

select.Parameters.Add("@attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("@taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = @attackCategory WHERE TaughtOn = @taughtOn";

using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
    DataTable dt = new DataTable();
    sda.Fill(dt);

    return dt;
}

sda.Fill(dt);在代码行上抛出异常。如果查询中未使用任何参数,则此代码有效:

string cmd = @"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";

代码2是:

string connectieString = dbConnection();

SqlConnection connection = new SqlConnection(connectieString);

SqlCommand select = new SqlCommand();
select.Connection = connection;

select.Parameters.Add("@attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("@ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = @attackCategory WHERE ID = @ID";

connection.Open();
object name = select.ExecuteScalar();
connection.Close();

return name;

异常在object name = select.ExecuteScalar();代码行上触发。如果在查询中使用 1 个参数,则此代码有效:

select.Parameters.Add("@ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=@ID";

标签: c#sqlsyntax-errorsqlconnectionsqlcommand

解决方案


您不能提供具有参数的表名,参数适用于带有列值的 where 子句。

string cmd = @"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";

但是,我们需要简化以在此查询中使用参数。

SqlCommand select = new SqlCommand();
 select.Connection = connection;
 select.Parameters.Add("@taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
 string cmd = @"select ID, Name from " + attackCategory + " where TaughtOn  =@taughtOn"; 
 select.CommandText = cmd;

在上面的 tsql 查询中,应用了字符串连接,并且表名包含在字符串中,这将起作用。

编辑:-

我明白为什么你的 sqlDataAdapter 没有识别参数。原因是你没有提供。是的,没错,您提供的CommandText不是select可变的命令对象。

我已经更正了你的代码。

select.Parameters.Add("@taughtOn", SqlDbType.VarChar, 50).Value = taughtOn; 
string cmd = @"select ID, Name from " + attackCategory + " where TaughtOn =@taughtOn"; 
select.CommandText = cmd; 
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select)) 
{ 
DataTable dt = new DataTable(); 
sda.Fill(dt); 
return dt; 
}

希望这可以帮助 !!


推荐阅读