Beispiel #1
0
        /// <summary>
        /// Executes a SQL query that returns a list of rows as the result.
        /// </summary>
        /// <param name="commandText">The MySQL query to execute</param>
        /// <param name="parameters">Parameters to pass to the MySQL query</param>
        /// <returns>A list of a Dictionary of Key, values pairs representing the
        /// ColumnName and corresponding value</returns>
        public List <Dictionary <string, string> > Query(string commandText, Dictionary <string, object> parameters)
        {
            List <Dictionary <string, string> > rows = null;

            if (String.IsNullOrEmpty(commandText))
            {
                throw new ArgumentException("Command text cannot be null or empty.");
            }

            try
            {
                EnsureConnectionOpen();
                var command = CreateCommand(commandText, parameters);

                using (NpgsqlDataReader reader = command.ExecuteReader())
                {
                    rows = new List <Dictionary <string, string> >();
                    while (reader.Read())
                    {
                        var row = new Dictionary <string, string>();
                        for (var i = 0; i < reader.FieldCount; i++)
                        {
                            var columnName  = reader.GetName(i);
                            var columnValue = reader.IsDBNull(i) ? null : reader.GetValue(i); //.GetString(i);
                            row.Add(columnName, GenericHelpers.NullToString(columnValue));
                        }
                        rows.Add(row);
                    }
                }
                EnsureConnectionClosed();
            }
            catch (NpgsqlException ex)
            {
                System.Console.WriteLine("Exception; " + ex.InnerException);
            }
            finally
            {
                EnsureConnectionClosed();
            }

            return(rows);
        }