C#mySQL参数不起作用



显然我的参数似乎不起作用(c#asp.net)。我的代码在comm.ExecuteScalar()上引发了一个异常。

MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''users'' at line 1'

这是我的源代码:

public int countRows(string table)
    {
        string cmdString = "SELECT COUNT(*) FROM @tbl";
        int count = -1;
        using (MySqlCommand comm = new MySqlCommand())
        {
            comm.Connection = conn;
            comm.CommandText = cmdString;
            comm.Parameters.AddWithValue("@tbl", "users");
            count = Convert.ToInt32(comm.ExecuteScalar());
        }
        return count;
    }

但是,当我使用它时,它可以很好地工作:

public int countRows(string table)
    {
        string cmdString = "SELECT COUNT(*) FROM users";
        int count = -1;
        using (MySqlCommand comm = new MySqlCommand())
        {
            comm.Connection = conn;
            comm.CommandText = cmdString;
            count = Convert.ToInt32(comm.ExecuteScalar());
        }
        return count;
    }

这已经使我疯狂了几个小时。谁能帮助我?

尝试此

string cmdString = string.Format("SELECT COUNT(*) FROM {0}", table);

最新更新