您好我正在尝试在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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以给你更多信息,谢谢
首先,您没有从方法返回任何内容.我想补充一下,你确定要返回一个SqlDataReader吗?它在一个使用区域内声明,因此无论如何它将在您返回时关闭.我认为你应该重新评估这个函数应该返回什么.
您有一个返回类型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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我已经注意到我看到的其他一些问题,您可以通过我的评论看到这些问题.
此外,我想指出一些非常重要的事情:你应该总是避免在查询中使用字符串连接,因为这会让你面临SQL注入攻击的风险(正如gmiley正式指出的那样).在这种情况下,您应该创建一个枚举,其中包含与所有可能的表名相关联的值,然后使用字典根据其枚举值查找表名.如果用户提供无效/未知值,则会抛出参数异常.
但这并不是你问题的结束(正如默认指出的那样).您无法在using
块中创建连接,块一旦退出块就会立即处理和关闭,然后使用SqlDataReader
从方法返回的连接.如果我是你,我会回来DataSet
而不是SqlDataReader
.这是我如何做到的:
首先,创建可能的表值的枚举:
public enum Table
{
FirstTable,
SecondTable
}
Run Code Online (Sandbox Code Playgroud)
还有一个字典,它将表枚举值映射到表名(您将在静态构造函数中填充):
private static Dictionary<Table, string> _tableNames = new Dictionary<Table, string>(); // populate this in your static constructor.
Run Code Online (Sandbox Code Playgroud)
然后这是获取数据的方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
最后一点,我建议你根据每个约定用较低的驼峰案例命名你的类级变量,例如_connectionString
.