Пример #1
0
        /// <summary>
        /// Execute a MySqlCommand that returns a resultset against the database specified in the connection string
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a MySqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static List <T> ExecuteReader <T>(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] commandParameters)
        {
            MySqlCommand    cmd  = new MySqlCommand();
            MySqlConnection conn = new MySqlConnection(connectionString);
            List <T>        tlst = new List <T>();

            // we use a try/catch here because if the method throws an exception we want to
            // close the connection throw code, because no datareader will exist, hence the
            // commandBehaviour.CloseConnection will not work
            try {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                using (MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    cmd.Parameters.Clear();
                    tlst = rdr.ConvertToList <T>();
                }
                return(tlst);
            }
            catch {
                conn.Close();
                throw;
            }
        }