C#:读取数据并将其添加到列表中

时间:2018-03-13 14:27:00

标签: c#

请帮我读取阅读器中的数据并将其插入列表。 Reader返回包含100列的1行。一切都很短。

  querysting = "select * from db2prod.questions where key_id =" + app.key_id;
  DB2cmd = new odbccommand(querystring,DBConn,DBtrans)
  DB2cmd.Commandtype = Commandtype.text
  DB2Rdr = DB2cmd.ExecuteReader;
   if(DB2Rdr.hasrows = true)
    {
      DB2Rdr.read();
      /* insert into the list
      /* compare if the 1st,3rd,5th,7th position is not null then insert in 
       a new table whose format is |key_idQues | Ans*/

1 个答案:

答案 0 :(得分:0)

应该这样做...... (对于MSSQL,但除了连接之外,主体是相同的)

private List<short> SQLColumnsToList()
    {
        using (var conn = new SqlConnection(/*Your connection string here*/))
        using (var cmd = conn.CreateCommand())
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from db2prod.questions where key_id = @keyID";

            cmd.Parameters.AddWithValue("keyID", /*Your ID here*/);

            conn.Open();
            using (var rdr = cmd.ExecuteReader())
            {
                if (rdr.Read())
                {
                    var list = new List<short>();
                    for (int i = 0; i < rdr.FieldCount; ++i)
                        list.Add(rdr.GetInt16(i));
                    return list;
                }
                throw new Exception("No row found");
            }
        }
    }