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!