SQL Server 从数据库读取的数据返回为“System.Data.SqlClient.SqlDataReader”

pkln4tw6  于 2022-12-17  发布在  其他
关注(0)|答案(1)|浏览(161)

我有一段代码,我试图从一个连接的数据库中获取符合条件的所有值,将它们存储到一个列表中,然后将它们作为选项输入到一个组合框中进行选择。
问题出在运行时,而不是数据库System.Data.SqlClient.SqlDataReader中的值。示例。
What is shown
What should be displayed
下面是正在使用的代码

public void fillMakeBox() // used to populate the Make Box of the car builder.
    {
        connection.Open(); // opens connection to the database
        List<String> makes =new List<string>();
        string makesQuery = "SELECT makeName from makes";
        SqlCommand makesSearch = new SqlCommand(makesQuery, connection);
        SqlDataReader myReader = makesSearch.ExecuteReader();
        while (myReader.Read()) // loops to add all values read to a list.
        {
            makes.Add(myReader.ToString());
        }
        
        while (makeSelection.SelectedItem != null)
        {
            List<String> filteredMakes = new List<string>();
            string searchMakesQuery = $"Select makeName from makes WHERE makeName LIKE {makeSelection.SelectedItem} %";
            SqlCommand searchMakeSearch = new SqlCommand(searchMakesQuery, connection);
            SqlDataReader myReaderFilter = makesSearch.ExecuteReader();
            while (myReaderFilter.Read())
            {
                filteredMakes.Add(myReaderFilter.ToString());
            }
            makes = filteredMakes;

        }
        makeSelection.DataSource = makes;

    }

我也试过使用makes.Add(myReader["makeName"].ToString());,但没有效果。

ekqde3dh

ekqde3dh1#

makes.Add(myReader.GetString(0));
//...
makes.Add(myReaderFilter.GetString(0));

另外,现在看起来好像在同一个连接上有两个活动的读取器;这通常是不可能的(除非启用MARS);您应该是using每个读取器(以及命令和连接),并确保在打开第二个读取器(myReaderFilter)之前释放第一个读取器(myReader

connection.Open(); // opens connection to the database
List<String> makes =new List<string>();
string makesQuery = "SELECT makeName from makes";
using (SqlCommand makesSearch = new SqlCommand(makesQuery, connection))
{
    using SqlDataReader myReader = makesSearch.ExecuteReader();
    while (myReader.Read()) // loops to add all values read to a list.
    {
        makes.Add(myReader.GetString(0));
    }
}

while (makeSelection.SelectedItem != null)
{
    List<String> filteredMakes = new List<string>();
    string searchMakesQuery = $"Select makeName from makes WHERE makeName LIKE {makeSelection.SelectedItem} %";
    using (SqlCommand searchMakeSearch = new SqlCommand(searchMakesQuery, connection))
    {
        using SqlDataReader myReaderFilter = makesSearch.ExecuteReader();
        while (myReader.Read())
        {
            makes.Add(myReaderFilter.GetString(0));
        }
    }
    makes = filteredMakes;

}
makeSelection.DataSource = makes;

此外,您不应该将数据连接到SQL查询中;这就是你如何得到SQL注入。请调查“参数”。或者也许只是使用像Dapper的工具,而不是所有这些:

makes.AddRange(conn.Query<string>("SELECT makeName from makes"));
makes.AddRange(conn.Query<string>("Select makeName from makes WHERE makeName LIKE @name + '%'",
    new { name = makeSelection.SelectedItem }));

相关问题