在C#中使用Prepare select语句

时间:2017-03-13 15:58:24

标签: c# mysql

我正在使用以下代码查询MySQL数据库。我需要替换我的select查询以准备语句

  public static void ValidateName(List<Employees> EmpList, string Grp)
    {
        var connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

        string selectQuery;

        for (int i = 0; i < EmpList.Count; i++)
        {
           selectQuery = "Select EmpName from Employee where group = @Grp  AND @Name in (FirstName, LastName);";
            using (MySqlConnection conn = new MySqlConnection(connStr))
            using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
            {
                cmd.Parameters.Add("@Grp", MySqlDbType.VarChar).Value = Grp;
                cmd.Parameters.Add("@Name", MySqlDbType.VarChar).Value = EmpList[i].Name;
                conn.Open();
                var reader = cmd.ExecuteReader();
                List<string> lineList = new List<string>();
                while (reader.Read())
                {
                    lineList.Add(reader.GetString(0));
                }
                if (lineList.Count <=0)
                {
                   WriteValidationFailure(EmpList[i], "Name doesnot exists in the DB");
                }
                conn.Close();
        }       
      }
    }

此代码完美无缺。但是为了改进,我需要使用prepare语句而不是我正在使用的查询。因为我在代码中进行了类似的各种验证,所以我不确定如何有效地重用这些参数。

1 个答案:

答案 0 :(得分:3)

你非常接近。只需调用cmd.Prepare(),保持对参数的引用,并重用命令:

public static void ValidateName(List<Employees> EmpList, string Grp)
{
    var connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

    string selectQuery;
    selectQuery = "Select EmpName from Employee where group = @Grp  AND @Name in (FirstName, LastName);";
    using (MySqlConnection conn = new MySqlConnection(connStr)) {
        conn.Open();
        using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
        {           
            var prmGrp = cmd.Parameters.Add("@Grp", MySqlDbType.VarChar);
            var prmName = cmd.Parameters.Add("@Name", MySqlDbType.VarChar);
            cmd.Prepare();
            for (int i = 0; i < EmpList.Count; i++)
            {
                prmGrp.Value = Grp;
                prmName.Value = EmpList[i].Name;

                using (var reader = cmd.ExecuteReader()) {
                    List<string> lineList = new List<string>();
                    while (reader.Read())
                    {
                        lineList.Add(reader.GetString(0));
                    }
                    if (lineList.Count <=0)
                    {
                        WriteValidationFailure(EmpList[i], "Name doesnot exists in the DB");
                    }
                }
            }           
        }
        conn.Close();
    }           
}