如何<String>从SQL查询生成列表?



如果我定义了一个DbCommand来执行类似的东西:

SELECT Column1 FROM Table1

生成返回记录List<String>的最佳方法是什么?

没有Linq等,因为我正在使用VS2005。

我认为这就是你要找的。

List<String> columnData = new List<String>();
using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

未测试,但这应该可以正常工作。

遍历项目并添加到集合中。您可以使用Add方法

List<string>items=new List<string>();
using (var con= new SqlConnection("yourConnectionStringHere")
{
    string qry="SELECT Column1 FROM Table1";
    var cmd= new SqlCommand(qry, con);
    cmd.CommandType = CommandType.Text;
    con.Open();
    using (SqlDataReader objReader = cmd.ExecuteReader())
    {
        if (objReader.HasRows)
        {              
            while (objReader.Read())
            {
              //I would also check for DB.Null here before reading the value.
               string item= objReader.GetString(objReader.GetOrdinal("Column1"));
               items.Add(item);                  
            }
        }
    }
}

或者嵌套列表(好吧,OP 适用于单列,这是针对多列的..):

        //Base list is a list of fields, ie a data record
        //Enclosing list is then a list of those records, ie the Result set
        List<List<String>> ResultSet = new List<List<String>>();
        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(qString, connection);
            // Create and execute the DataReader..
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                var rec = new List<string>();
                for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
                {                      
                    rec.Add(reader.GetString(i));
                }
                ResultSet.Add(rec);
            }
        }

如果要查询所有列

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

用户的构造函数将执行所有"dr.GetString(i)"

其中返回的数据是字符串;您可以转换为其他数据类型:

(from DataRow row in dataTable.Rows select row["columnName"].ToString()).ToList();

这个版本与@Dave Martin的目的相同,但它更干净,获取所有列,并且如果您不想将其放在电子邮件,视图等上,则易于操作数据。

List<string> ResultSet = new List<string>();
using (SqlConnection connection = DBUtils.GetDBConnection())
{
    connection.Open();
    string query = "SELECT * FROM DATABASE";
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
             while (reader.Read())
             {
                  var rec = new List<string>();
                  for (int i = 0; i <= reader.FieldCount - 1; i++)
                  {
                       rec.Add(reader.GetString(i));
                  }
                  string combined = string.Join("|", rec);
                  ResultSet.Add(combined);
             }
        }
    }
}
现在可以

使用 1 个代码行

List<string>? columnData = await UkrGuru.SqlJson.DbHelper.ExecAsync<List<string>>(@"DECLARE @Data varchar(max) = '[]'; 
    SELECT @Data = JSON_MODIFY(@Data , 'append $', Column1) FROM Table1; SELECT @Data;");

相关内容

  • 没有找到相关文章

最新更新