C#和MySQL-语法不正确?

C#和MySQL-语法不正确?,c#,mysql,syntax,C#,Mysql,Syntax,假设我在我的MySQLOperations类中使用此方法: public bool checkIfRowExists(string tableName, string columnToLookIn, string dataToLookFor) { string myConnectionString = "Server = " + server + "; Database = " + dbName + "; UID = " + user + "; Password

假设我在我的
MySQLOperations
类中使用此方法:

    public bool checkIfRowExists(string tableName, string columnToLookIn, string dataToLookFor)
    {
        string myConnectionString = "Server = " + server + "; Database = " + dbName + "; UID = " + user + "; Password = " + password + ";";
        int isExisting = 0;
        using (MySqlConnection myConnection = new MySqlConnection(myConnectionString))
        {
            using (MySqlCommand myCommand = new MySqlCommand("SELECT EXISTS (SELECT 1 FROM @tablename WHERE @columnname = @data);", myConnection))
            {
                myCommand.Parameters.AddWithValue("@tablename", tableName);
                myCommand.Parameters.AddWithValue("@columnname", columnToLookIn);
                myCommand.Parameters.AddWithValue("@data", dataToLookFor);
                try
                {
                    myConnection.Open();
                    isExisting = (int)myCommand.ExecuteScalar();
                    myConnection.Close();
                }
                catch (Exception ex)
                {
                    myConnection.Close();
                    MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return (isExisting == 1);
            }
        }
    }
在另一个类中,我创建了一个
MySQLOperations
对象。 我在if语句中调用了这个方法:
if(objSQLOperations.checkIfRowExists(“tblInventory”、“ItemID”、txtimeid.Text))
。让我们假设txtItemID包含一个有效的10位数字。在我的数据库中,我有一个名为
tblInventory
的表,其中有一列
ItemID

我的问题是catch块中的语句执行,表示我的SQL语法有错误。“您的SQL语法有错误;请检查与您的MySQL服务器版本对应的手册,以了解在“tblInventory”附近使用的正确语法,其中当我的txtItemID包含文本“1111111111”时,会在消息框中弹出‘ItemID’=‘11111111’。”


我相信我的
SELECT EXISTS
语句是正确的。

否您不能将参数用于表名或列名。您必须通过连接动态地构建SQL字符串

比如:

当然,如果用户可以输入
tableName
columnname-tolookin
,这将打开您的窗口。但是,如果
tableName
columnnametookin
仅在示例中显示的代码中设置,则这不是问题

相关的:


我想我不能将参数用于表名或列名。如果是,是否有解决办法?
var sql = "SELECT EXISTS(SELECT 1 FROM " + tablename + 
           " WHERE " + columnNameToLookIn + " = @data);"
using (MySqlCommand myCommand = new MySqlCommand(sql, myConnection))