C#getAll函数建议

本文关键字:函数 C#getAll | 更新日期: 2023-09-27 18:26:17

嗨,我正试图在C#中创建CRUD函数,但我的第一个函数是FetchALL,因为到目前为止,它说不是所有代码路径都返回值。

这是我到目前为止的代码

  public SqlDataReader FetchAll(string tableName)
        {  

        using (SqlConnection conn = new SqlConnection(_ConnectionString,))
    { 
    string query = "SELECT * FROM  " + tableName;
    SqlCommand command = new SqlCommand(query, conn);
    using (SqlDataReader reader = command.ExecuteReader())
    conn.Open();

    conn.Close();
           }
        }
    }
}

我可以给你更多的信息,谢谢

C#getAll函数建议

您有一个SqlDataReader的返回类型,但您的代码中没有返回任何内容。至少你应该声明你的数据读取器并像这样返回:

public SqlDataReader FetchAll(string tableName)
{
    SqlDataReader reader;
    using (SqlConnection conn = new SqlConnection(_ConnectionString))
    {
        string query = "SELECT * FROM  " + tableName;
        // added using block for your command (thanks for pointing that out Alex K.)
        using (SqlCommand command = new SqlCommand(query, conn))
        {
            conn.Open(); // <-- moved this ABOVE the execute line.
            reader = command.ExecuteReader(); // <-- using the reader declared above.
            //conn.Close(); <-- not needed.  using block handles this for you.
        }
    }
    return reader;
}

注意,我也注意到了我看到的其他一些问题,你可以从我的评论中看到。

此外,我想指出一件非常重要的事情:您应该始终避免查询中的字符串串联,因为这会使您面临SQL注入攻击的风险(正如gmiley适时指出的那样)。在这种情况下,您应该创建一个包含与所有可能的表名关联的值的枚举,然后使用字典根据其枚举值查找表名。如果用户提供了无效/未知的值,则会引发参数异常。


不过,这并不是你问题的结束(正如Default所指出的那样)。不能在using块中创建连接,该块在退出块后立即释放并关闭,然后使用从该方法返回的SqlDataReader。如果我是你,我会返回DataSet而不是SqlDataReader。以下是我的做法:

首先,创建可能的表值的枚举:

public enum Table
{
    FirstTable,
    SecondTable
}

以及一个将表枚举值映射到表名称的字典(您将在静态构造函数中填充):

private static Dictionary<Table, string> _tableNames = new Dictionary<Table, string>(); // populate this in your static constructor.

然后这里是你获取数据的方法:

public static System.Data.DataSet FetchAll(Table fromTable)
{
    var ret = new System.Data.DataSet();
    using (var conn = new System.Data.SqlClient.SqlConnection(_connectionString))
    {
        string tableName = "";
        if (!_tableNames.TryGetValue(fromTable, out tableName)) throw new ArgumentException(string.Format(@"The table value ""{0}"" is not known.", fromTable.ToString()));
        string query = string.Format("SELECT * FROM {0}", tableName);
        using (var command = new System.Data.SqlClient.SqlCommand(query, conn))
        {
            using (var adapter = new System.Data.SqlClient.SqlDataAdapter(command))
            {
                adapter.Fill(ret);
            }
        }
    }
    return ret;
}

最后要注意的是,我建议您按照惯例用小写字母命名类级变量,例如_connectionString

首先,您没有从该方法返回任何内容。我想补充一点,你确定要返回SqlDataReader吗?它是在using块中声明的,所以在您返回它时它将被关闭。我认为你应该重新评估这个函数应该返回什么。

您需要一个返回语句,让方法返回一个值。