0

Apparently my parameter doesn't seem to be working (C# ASP.NET). My code throws an exception at 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'

this is my source code:

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;
    }

Yet when i use this it works perfectly fine:

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;
    }

This has been driving me crazy for hours now. Anyone who could help me out?

murdoch
  • 33
  • 1
  • 6

1 Answers1

0

Try This

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

Sumit patel
  • 3,807
  • 9
  • 34
  • 61
Hamad
  • 161
  • 1
  • 3
  • 7