我在本网站和其他地方查看过许多类似的问题,但是没有一个问题对我有帮助。
我正在尝试通过查询建立数据库连接,但出现错误
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";
您不能提供具有名称的表名称参数,该参数适用于带有列值的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
可变的Command Object 。
我已更正您的代码。
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;
}
希望这可以帮助 !!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句