SqlDataReader打印多行,我该如何拆分?

时间:2015-08-08 02:21:40

标签: c# sql asp.net sql-server sqldatareader

我想使用SqlDataReader从数据库中检索数据。我得到了它的工作,但我的查询返回多行数据,我想分开它。

这是我的代码

string query = "select title, rating, dor from movie where title like '%"+name+"%';";

using (SqlConnection conn = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();

    SqlDataReader reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
        while (reader.Read())
        {
            Response.Write(reader[0].ToString());
            Response.Write(reader[1].ToString());
            Response.Write(reader[2].ToString());
        }
    }
    else
    {
        Response.Write("No rows found");
    }

    reader.Close();
}

所以例如.. reader[0].ToString()是标题,因为它返回多行数据,它打印“title1title2”。有没有办法分割这个,所以第1行的标题与第2行的标题分开?

1 个答案:

答案 0 :(得分:0)

试试这个

string query = "select title, rating, dor from movie where title like '%"+name+"%';";

using (SqlConnection conn = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();

    SqlDataReader reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
        while (reader.Read())
        {
            Response.Write(reader[0].ToString());
            Response.Write(reader[1].ToString());
            Response.Write(reader[2].ToString());
            Response.Write("------------------------");//whatever separator you want to use
        }
    }
    else
    {
        Response.Write("No rows found");
    }

    reader.Close();
}