0

I simply would like a function that returns records from table passing parameters - field names and query. I am using sqldatareader() however the problem is if the results return null it does not work.

So the end result should be for example: (which works except if it returns null or empty)

SqlDataReader user = bw.fetchReader("Firstname, Surname", "Staff");

string firstname = user["Firstname"];
string surname = user["Surname"];

As an alternative can I use string[] array instead? I would rather use string[] array for example:

string[] user = bw.fetchReader("Firstname, Surname", "Staff");

string firstname = user["Firstname"];
string surname = user["Surname"];

This is the code:

    public SqlDataReader fetchReader(string fields, string table, string where = null, int count = 0)
    {

        string strDBConn = db.getDBstring(Globals.booDebug);
        SqlConnection conn = new SqlConnection(strDBConn);

        using (SqlCommand cmd = new SqlCommand())
        {
            string whereClause = where != null ? " WHERE " + where : "";
            string countRows = count != 0 ? "count(*) as " + fields : fields;

            cmd.CommandText = "SELECT " + countRows + " FROM " + table + whereClause;

            //HttpContext.Current.Response.Write(cmd.CommandText + "<br>");

            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            conn.Open();

            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            if(reader.Read())
            {
                return reader;

            }
            else
            {
                return null;
            }
        }
    }

Any help appreciated!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Karim Ali
  • 97
  • 1
  • 10
  • The fact that you need this layer indicates that you have a design problem higher up in your code. Why do you have this wrapper? As for your actual question, you could read all data into a dictionary, or alternatively, compare the method's return value to `null` using an `if()`. – CodeCaster Oct 26 '16 at 14:17
  • I did that but it doesn't work. It loops forever. – Karim Ali Oct 26 '16 at 15:01
  • This plan will force you to build code that is crazy-vulnerable to sql injection attacks. Go for a pattern more like this, which encourages parameterized queries: http://stackoverflow.com/questions/850065/return-datareader-from-datalayer-in-using-statement/850121#850121 – Joel Coehoorn Oct 26 '16 at 18:59

0 Answers0