使用函数返回sqldatareader或string []数组

时间:2016-10-26 14:09:32

标签: c# function return sqldatareader

我只想要一个从表传递参数返回记录的函数 - 字段名称和查询。我正在使用sqldatareader()但问题是如果结果返回null则不起作用。

所以最终的结果应该是例如:(除非它返回null或为空,否则它起作用)

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

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

作为替代方法,我可以使用string []数组吗?我宁愿使用string []数组,例如:

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

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

这是代码:

    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;
            }
        }
    }

任何帮助表示赞赏!

0 个答案:

没有答案