【问题标题】:SqlDataReader to populate structSqlDataReader 填充结构
【发布时间】:2014-03-20 05:51:12
【问题描述】:

有一个私有的“Employee”类对象反映了公共结构“empStruct”。我需要使用 SQLReader 从查询中读取行值以填充结构,然后将对象设置为等于结构值。我认为有一种更简单的方法,但我对此很陌生。

public struct empStruct
    {
        public int eid;
        public string lastname;
        public string firstname;
        public DateTime birthdate;
        public DateTime hiredate;
        public bool ishourly;
        public decimal payrate;
    }
        public static bool SelectEmployee(int eid)
    {
        empStruct SelectRecord = new empStruct();
        Employee newEmp = new Employee();
        string sqlText;

        sqlText = "SELECT EID,EID, LastName, FirstName, BirthDate, HireDate, IsHourly, PayRate ";
        sqlText += "FROM Employee ";
        sqlText += "WHERE EID = @EID ";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {

            SqlCommand command = new SqlCommand(sqlText, connection);
            command.CommandType = CommandType.Text;
            command.Parameters.AddWithValue("@EID", eid);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            //Call Read before accessing data.
            while (reader.Read())
            {
                ???
            }
            newEmp = SelectRecord;

        }

我知道“//Call Read...”之后的所有内容都不完整,我无法弄清楚这个阅读器是如何工作的。

【问题讨论】:

    标签: c# sql-server struct visual-studio-2013 sqldatareader


    【解决方案1】:
    while (reader.Read())
    {
    newEmp.eid = (int)reader("EID");
    newEmp.firstname = (string)reader("FirstName");
    ....
    }
    

    【讨论】:

      【解决方案2】:

      也许像这样加载结构

      while (reader.Read())            {
         newEmp.lastname = reader.GetString(1);
         newEmp.firstname  = reader.GetString(2);
      
      
      }
      

      【讨论】:

      • 你能详细说明一下这是如何回答这个问题的吗?
      猜你喜欢
      • 2011-08-13
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      • 2012-08-14
      相关资源
      最近更新 更多