如何从SqlDataReader获取值以进行循环执行?

时间:2014-08-29 12:09:58

标签: c#-4.0

这里我编写了从数据库到SqlDataReader获取每个StudyUID(作为字符串),但我需要知道reader值如何调用forloop执行。 阅读每个StudyUID以便执行。这是代码:。

 public void automaticreport()
    {
        //string autsdyid="";
        SqlConnection con = new SqlConnection(constr);
        con.Open();
        string autoquery = "Select StudyUID From StudyTable Where status='2'";
        SqlCommand cmd = new SqlCommand(autoquery, con);
        SqlDataReader rdr = cmd.ExecuteReader();
        for()
        {
            //how to call each StudyUId from database through for loop

        if (!this.reportchk)
        {
            Reportnew cf = new Reportnew();
            ThreadPool.QueueUserWorkItem((WaitCallback)(o => cf.ReportRetrive(this, autsdyid, true)));
        }
        else
        {
            int num = (int)System.Windows.Forms.MessageBox.Show("Reports checking in progress, Please wait sometime and try again later", "OPTICS", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        con.Close();
    }

4 个答案:

答案 0 :(得分:0)

if (rdr.HasRows)
{
    while (rdr.Read())
    {
         Console.WriteLine(rdr.getString("columnName"));
    }
}

答案 1 :(得分:0)

您可以像这样使用while循环:

while (rdr.Read())
{
  string s = rdr.GetString(rdr.GetOrdinal("Column"));
//Apply logic to retrieve here
}

答案 2 :(得分:0)

您可以使用以下内容:

while (reader.Read())
{
    string value = reader.getString("columnName");
}

答案 3 :(得分:0)

与@ R.T和其他人一样,您可以在数据阅读器上使用Read方法。查看示例代码,您可能需要稍微重构以满足更多SOLID原则,并确保您没有泄漏数据库连接

这是一个已经重构的代码示例。

public void automaticreport()
{
    foreach (var autsdyid in LoadStudyIdentifiers())
    {
        if (!this.reportchk)
        {
            Reportnew cf = new Reportnew();
            ThreadPool.QueueUserWorkItem((WaitCallback)(o => cf.ReportRetrive(this, autsdyid, true)));
        }
        else
        {
            int num = (int)System.Windows.Forms.MessageBox.Show("Reports checking in progress, Please wait sometime and try again later", "OPTICS", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
    }
}

private string[] LoadStudyIdentifiers()
{
    var results = new List<string>();

    // adding a using statement will close the database connection if there are any errors
    // avoiding consuming the database connection pool 
    using (var con = new SqlConnection(constr)) 
    {
        conn.Open();
        var autoquery = "Select StudyUID From StudyTable Where status='2'";

        using (var cmd = new SqlCommand(autoquery, con)) 
        {
            SqlDataReader rdr = cmd.ExecuteReader();
            while(rdr.Read())
            {
                results.Add(rdr.GetString(rdr.GetOrdinal("StudyUID")));
            }
        }
    }

    return results.ToArray();
}

注意:我在记事本中写了这个,所以不能保证它会编译,但应该说明你如何重构你的代码。