C# Prepared SQL 语句不替换@Value
C# Prepared SQL Statement does not replace @Value
我得到了这个代码:
command = new SQLiteCommand(dbConnection);
sql = "SELECT IFNULL(MAX(RowId), 1) AS Id FROM @name";
SQLiteParameter nameParam = new SQLiteParameter("@name", System.Data.DbType.String, 100);
command.CommandText = sql;
command.Parameters.Add(nameParam);
command.Prepare();
foreach (String name in liste)
{
command.Parameters[0].Value = name;
int number = Convert.ToInt32(command.ExecuteScalar());
ret = ret + number;
}
dbConnection.Close();
return ret;
我做错了什么?执行此语句时,我总是会遇到以下异常:
"near "@name": syntax error".
所以这意味着 SQLstatement 没有被准备好的语句参数更新,这是为什么?
您不能将 table 名称作为参数传递。
你可以在形成SQL语句时将它添加到字符串中,但是你运行有SQL注入的风险,所以不要这样做。
您可以做的另一件事是让用户 select 从下拉菜单中选择 table 并创建 SQL 这样做,因为您已经知道所有可能的 tables.
我得到了这个代码:
command = new SQLiteCommand(dbConnection);
sql = "SELECT IFNULL(MAX(RowId), 1) AS Id FROM @name";
SQLiteParameter nameParam = new SQLiteParameter("@name", System.Data.DbType.String, 100);
command.CommandText = sql;
command.Parameters.Add(nameParam);
command.Prepare();
foreach (String name in liste)
{
command.Parameters[0].Value = name;
int number = Convert.ToInt32(command.ExecuteScalar());
ret = ret + number;
}
dbConnection.Close();
return ret;
我做错了什么?执行此语句时,我总是会遇到以下异常:
"near "@name": syntax error".
所以这意味着 SQLstatement 没有被准备好的语句参数更新,这是为什么?
您不能将 table 名称作为参数传递。
你可以在形成SQL语句时将它添加到字符串中,但是你运行有SQL注入的风险,所以不要这样做。
您可以做的另一件事是让用户 select 从下拉菜单中选择 table 并创建 SQL 这样做,因为您已经知道所有可能的 tables.