C#和MySQL - 语法不正确?

时间:2014-09-14 02:56:07

标签: c# mysql syntax

假设我的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", txtItemID.Text))。我们假设txtItemID包含有效的10位数字。在我的数据库中,我有一个名为tblInventory的表,其中包含ItemID列。

我的问题是我的catch块中的语句执行,说我的SQL语法有错误。 “您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以便在第1行''tblInventory'附近使用'ItemID'='11111111111''附近使用正确的语法。”当我的txtItemID包含文本“1111111111”时,会弹出一个MessageBox。

我相信我的SELECT EXISTS陈述是正确的。

1 个答案:

答案 0 :(得分:1)

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

像:

var sql = "SELECT EXISTS(SELECT 1 FROM " + tablename + 
           " WHERE " + columnNameToLookIn + " = @data);"
using (MySqlCommand myCommand = new MySqlCommand(sql, myConnection))

如果可以由用户输入tableNamecolumnNameToLookIn,这当然会让您最多SQL injection。但是,如果tableNamecolumnNameToLookIn仅在您的示例中显示的代码中设置,那么这不是问题。

相关:

use a variable for table name in mysql sproc

Dynamic table names in stored procedure function