【问题标题】:C# ASP Dot Net 4.5 prepared statements with MySQLC# ASP Dot Net 4.5 使用 MySQL 准备的语句
【发布时间】:2016-03-02 00:33:29
【问题描述】:

My Class CRUD 有以下方法:

 public bool dbQuery(string sql,string[] paramList= null)
{
    bool flag = false;
    try
    {
        connect();
        cmd = new MySqlCommand(sql,con);
        cmd.Prepare();
        if(paramList != null)
        {
         foreach(string i in paramList){
                string[] valus = i.Split(',');
                string p = valus[0];
                string v = valus[1];
                cmd.Parameters.AddWithValue(p,v);
            }
         }
        if (cmd.ExecuteNonQuery() > 0)
        {
            flag = true;
        }
    }
    catch (Exception exc)
    {
        this.error(exc);
    }
    finally
    {
        try
        {
            closeCon();
        }
        catch (Exception excf)
        {
            this.error(excf);
        }
    }
    return flag;
}

我通过以下方式发送查询:

 string sql = "SELECT * FROM dept_login WHERE (user_email = ?user_email OR user_cell = ?user_cell ) AND userkey = ?userkey";
    string[] param = new string[] {
         "\"?user_email\",\""+ userid.Text.ToString()+"\"" ,
         "\"?user_cell\",\""+ userid.Text.ToString()+"\"" ,
         "\"?userkey\",\""+ userkey.Text.ToString()+"\""
    };
    
    if (db.dbQuery(sql, param))
    {
        msg.Text = "Ok";
    }
    else
    {
        msg.Text = "<strong class='text-danger'>Authentication Failed</strong>";
    }

但它说的是

Parameter "?user_email" must be defined"

我做错了什么?有没有最好的方法将它与参数一起使用来搜索、插入、更新和或删除 MySQL 数据库中的记录。我在具有 64 位、MySQL Server 5.6.21 的 Windows 10 上使用带有 Dot Net Framework 4.5 的 Visual Studio 2015。

【问题讨论】:

    标签: c# mysql asp.net visual-studio


    【解决方案1】:

    当您将此值传递给您的 dbQuery() 方法时:

    "\"?user_email\",\""+ userid.Text.ToString()+"\""
    

    它最终将这样的东西传递给AddWithValue()

    cmd.Parameters.AddWithValue("\"?user_email\"", "\"123\"");
    

    删除转义的引号,然后重试。

    string[] param = new string[] {
        string.Format("{0},{1}", "?user_email", userid.Text),
        string.Format("{0},{1}", "?user_cell", userid.Text),
        string.Format("{0},{1}", "?userkey", userkey.Text)
    };
    

    【讨论】:

    • 亲爱的@Grant Winney 我已经按照你的建议做了,但现在它说“参数”?user_email“在集合中找不到”?
    • string[] param = new string[] { "?user_email,"+ userid.Text.ToString(), "?user_cell,"+ userid.Text.ToString(), "?userkey, "+ userkey.Text.ToString() };现在工作谢谢
    【解决方案2】:

    我已将我定义的数组更改为以下内容:

     string[] param = new string[] {
             "?user_email,"+ userid.Text.ToString(),
             "?user_cell,"+ userid.Text.ToString(),
             "?userkey,"+ userkey.Text.ToString()
        };
    

    @Grant Winney 的答案是正确的,但是他在字符串参数之外定义了逗号......任何方式都感谢@Grant Winney

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 2011-12-13
      • 2012-12-18
      相关资源
      最近更新 更多