c# - SqlDataReader 读入 List<string>

标签 c# sql wcf ado.net sql-server-express

我正在用 C# 编写一个方法来从 WCF 服务查询 SQL Server Express 数据库。我必须使用 ADO.NET 来执行此操作(然后稍后使用 LINQ 重写它)。

该方法采用两个字符串 (fname, lname),然后从匹配记录中返回一个“Health Insurance NO”属性。我想将其读入列表(还有一些其他属性要检索)。

当前代码返回一个空列表。我哪里错了?

public List<string> GetPatientInfo(string fname, string lname)
{
    string connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\xxxx\\Documents\\Visual Studio 2010\\Projects\\ADOWebApp\\ADOWebApp\\App_Data\\ADODatabase.mdf;Integrated Security=True;User Instance=True";

    SqlConnection conn = new SqlConnection(connString);

    string sqlquery = "SELECT Patient.* FROM Patient WHERE ([First Name] = '"+fname+"') AND ([Last Name] = '"+lname+"')";
    SqlCommand command = new SqlCommand(sqlquery, conn);
    DataTable dt = new DataTable();

    List<string> result = new List<string>();

    using (conn)
    {
        conn.Open();

        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader != null && reader.Read())
            {
               dt.Load(reader);
               result.Add(Convert.ToString(reader["Health Insurance NO"]));
            }
        }
     }

     return result;
}

最佳答案

您正在尝试通过 DataTable.Load >循环<加载DataTable。你只需要一次。您还在循环中使用了 reader.Read()SqlDataReader.Read()使读者前进到下一条记录而不使用它。如果您要使用 DataTable.Load,则无需先阅读阅读器。因此,您只需完全删除循环即可加载表格。

但是因为你想返回一个列表你根本不需要DataTable,只需要循环阅读器:

List<string> result = new List<string>();
using (conn)
{
    conn.Open();
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            result.Add(Convert.ToString(reader["Health Insurance NO"]));
        }
    }
}

除此之外,您可以在没有 sql 参数的情况下进行 sql 注入(inject)。

关于c# - SqlDataReader 读入 List<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19299935/

相关文章:

c# - BinaryWriterWith7BitEncoding & BinaryReaderWith7BitEncoding

c# - 加速插入 - 一次插入列表

sql - 按时间限制SQL结果,MySQL

c# - 使用 System.ServiceModel 在 Xamarin 中使用 WCF REST 基本身份验证服务

.net - WCF 绑定(bind) - 太多了!我该如何选择?

时间:2019-05-07 标签:c#8switch表达式: No best type was found for the switch expression

c# - List<T> 和 IQueryable<T> 之间的执行差异

c# - CancellationToken.Register 作为事件通知机制与标准 .NET 事件模式

mysql - 为组选择 SUM() 的 Max()

javascript - 将 SignalR 与自托管 WCF 结合使用并通过 HTML 客户端使用集线器代理