SQL DataReader不能读取所有列,也不能写入文件

本文关键字:也不能 文件 不能 DataReader 不能读 读取 SQL | 更新日期: 2023-09-27 18:06:09

尽管我的DataReader似乎正确地解释了值(几乎),但它缺少一列,而不是写入文件,并且在最后一行抛出

+ base {"Invalid attempt to read when no data is present."} System.SystemException {System.InvalidOperationException}

退出while sqlReader.Read()循环

myCommand.CommandText = "use sis_comparison_data select reg_batch_uid, user_id_reg, reg_first, reg_mid, reg_last, reg_email, reg_stu_id, registrar_row_status from sis_temp where bb_row_status is null";
string bb_users = @"C:'BB_USERS.bbd";

  using (StreamWriter file = new StreamWriter(bb_users, false))
  {
    file.WriteLine("SYSTEM_ROLE|INSTITUTION_ROLE|EXTERNAL_PERSON_KEY|USER_ID|PASSWD|FIRSTNAME|MIDDLENAME|LASTNAME|EMAIL|STUDENT_ID|ROW_STATUS");
    using (SqlDataReader sqlReader = myCommand.ExecuteReader())
            {
            while (sqlReader.Read())
                {
                    file.WriteLine("none|student|", sqlReader["reg_batch_uid"].ToString() + "|" + sqlReader["user_id_reg"].ToString() + "|" + sqlReader["reg_stu_id"].ToString() + "|" + sqlReader["reg_first"].ToString() + "|" + sqlReader["reg_mid"].ToString() + "|" + sqlReader["reg_last"].ToString() + "|" + sqlReader["reg_email"].ToString() + "|" + sqlReader["reg_stu_id"].ToString() + "|" + sqlReader["registrar_row_status"].ToString());
                }
                sqlReader.Close();
            }             
   }

我的代码正在创建文件并编写第一行,并且在它之后只编写"none|student|"。无论出于什么原因,它没有拾取registrar_row_status列。

SQL查询工作,因为我一直在做所有的SQL脚本之前实现它到代码。

这是分步执行代码时的调试输出。

+       sqlReader   {System.Data.SqlClient.SqlDataReader}   System.Data.SqlClient.SqlDataReader
        sqlReader["reg_batch_uid"]  "johndoe"   object {string}
        sqlReader["reg_email"]  "jdoe@com.edu"  object {string}
        sqlReader["reg_first"]  "john"  object {string}
        sqlReader["reg_last"]   "doe"   object {string}
        sqlReader["reg_mid"]    ""  object {string}
        sqlReader["reg_stu_id"] "1234567"   object {string}
        sqlReader["user_id_reg"]    "johndoe"   object {string}

可以看到,缺少registrar_row_status

SQL DataReader不能读取所有列,也不能写入文件

我相信StreamWriter.WriteLine过载的第一个参数需要是一个格式字符串。

试试这个:

 file.WriteLine("none|student|" + sqlReader["reg_batch_uid"].ToString() + "|" + sqlReader["user_id_reg"].ToString() + "|" + sqlReader["reg_stu_id"].ToString() + "|" + sqlReader["reg_first"].ToString() + "|" + sqlReader["reg_mid"].ToString() + "|" + sqlReader["reg_last"].ToString() + "|" + sqlReader["reg_email"].ToString() + "|" + sqlReader["reg_stu_id"].ToString() + "|" + sqlReader["registrar_row_status"].ToString());
相关文章: