where子句和多个参数C#?

时间:2015-05-04 10:45:25

标签: c# sql inner-join where-clause

是否可以组合一个带有两个不同参数的WHERE子句?我必须将两个参数传递给此查询以进行连接。

这是我的代码:

using (var conn = new MySqlConnection(connStr))
{
    string sSQL = "SELECT * FROM head_doc h INNER JOIN doc_details d ON h.id_doc = d.id_doc INNER JOIN clients c ON c.id_client = h.id_client WHERE t.id_doc="+  Session["id_doc"].ToString()+  "AND id_client="+ Session["id_client"].ToString());
    MySqlCommand cmd = new MySqlCommand(sSQL, conn);
    cmd.CommandType = CommandType.Text;
    MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
    adp.Fill(dt);
}

显然我不能这样做,因为mysql拒绝这种语法。我怎么能以不同的方式做到这一点?

4 个答案:

答案 0 :(得分:2)

你需要引号和空格:

 string sSQL = "SELECT * FROM head_doc h INNER JOIN doc_details d ON h.id_doc = d.id_doc INNER JOIN clients c ON c.id_client = h.id_client WHERE t.id_doc='"+  Session["id_doc"].ToString()+  "' AND id_client='"+ Session["id_client"].ToString()+"'");

但更好的使用参数:

string sSQL = "SELECT * FROM head_doc h INNER JOIN doc_details d ON h.id_doc = d.id_doc INNER JOIN clients c ON c.id_client = h.id_client WHERE t.id_doc=@par1 AND id_client=@par2");

        MySqlCommand cmd = new MySqlCommand(sSQL, conn);
        cmd.Parameters.AddWithValue("@par1", Session["id_doc"].ToString());
        cmd.Parameters.AddWithValue("@par2", Session["id_client"].ToString());
        cmd.CommandType = CommandType.Text;
        ...

修改 如果两个表中确实存在id_client字段,则使用:

string sSQL = "SELECT * FROM head_doc h INNER JOIN doc_details d ON h.id_doc = d.id_doc INNER JOIN clients c ON c.id_client = h.id_client WHERE t.id_doc=@par1 AND h.id_client=@par2");

答案 1 :(得分:0)

尝试更改

"AND id_client

" AND id_client

第一个参数后缺少空格可能会出现问题。

答案 2 :(得分:0)

可能是的,这里最好的建议是Nerd Nord提到的参数。 但是我注意到" t.id_doc"这意味着id_doc来自表t,在你的选择中我看不到别名为t的表。 因此,请使用参数语法,并为id_doc找到合适的表别名。

答案 3 :(得分:0)

谢谢大家。这是我最终使用的(工作)代码。

        using (var conn = new MySqlConnection(connStr))
        {
            string sSQL = "SELECT * FROM head_doc h INNER JOIN doc_details d ON h.id_doc = d.id_doc INNER JOIN clients c ON c.id_clients = h.id_clients WHERE h.id_doc=@par1 AND c.id_client=@par2";
            MySqlCommand cmd = new MySqlCommand(sSQL, conn);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add(new MySqlParameter("@par1", Session["id_doc"].ToString()));
            cmd.Parameters.Add(new MySqlParameter("@par2", Session["id_client"].ToString()));
            MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
            adp.Fill(dt);
        }