2013-08-01 48 views
-4

我有一个SQL Server 2008数据库,我正在后端工作。我正在研究asp.net/C#我如何使用SqlDataReader读取数据

using (SqlCommand StrQuer = new SqlCommand("SELECT * FROM [shopcart].[dbo].[user] WHERE [email protected] AND [email protected]", myconn)) 
{ 
    StrQuer.Parameters.AddWithValue("@userid", str_usr); 
    StrQuer.Parameters.AddWithValue("@password", str_psd); 

    SqlDataReader dr = StrQuer.ExecuteReader(); 

    if (dr.HasRows) 
    { 
     // MessageBox.Show("loginSuccess");  
    } 
} 

我知道读者有价值。我的SQL命令是从表中选择一行。我想逐一阅读阅读器中行中的项目。我该怎么做呢?

感谢

+0

简单地使用DR [“列名”] –

+0

这样类型的问题,我不认为应该在这里得到解答,非常基本的东西可以先搜索 –

回答

1

您可以在循环中使用dr.Read()。

while(dr.Read()) 
{ 
    string firstCell = dr[0].ToString(); 
    string secondCell = dr[1].ToString(); 

    // and so on... 
} 

// It will be better if you close DataReader 
dr.Close(); 
+0

http://stackoverflow.com/questions得到答案/ 4018114/read-data-from-sqldatareader –

1

您可以使用FieldCount属性:

if (dr.Read()) 
{ 
    for (int i = 0; i < dr.FieldCount; i++) 
    { 
     var value = dr[i]; 
     // do something 
    } 
} 
+0

http://stackoverflow.com/questions/4018114/read-data-from-sqldatareader –

0

这里是SqlDataReader对象的完整的例子。

SqlConnection myConnection = new SqlConnection(); 
     myConnection.ConnectionString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString; 
     SqlCommand myCommand = new SqlCommand(); 
     myCommand.CommandType = CommandType.Text; 
     myCommand.CommandText = "SELECT CategoryID, CategoryName FROM Categories"; 
     myCommand.Connection = myConnection; 
     SqlDataReader myReader; 

     try 
     { 
      myConnection.Open(); 
      myReader = myCommand.ExecuteReader(); 
      while (myReader.Read()) 
      { 
       ListItem li = new ListItem(); 
       li.Value = myReader["CategoryID"].ToString(); 
       li.Text = myReader["CategoryName"].ToString(); 
       ListBox1.Items.Add(li); 
      } 
      myReader.Close(); 
     } 
     catch (Exception err) 
     { 
      Response.Write("Error: "); 
      Response.Write(err.ToString()); 
     } 
     finally 
     { 
      myConnection.Close(); 
     } 
+2

这是一个可怕的例子。这里有不少于3个'IDisposable'资源,你不需要'Dispose'。请阅读'using'语句的精细手册。 –

0

把列的名称开始从那里“的ColumnName”是数据库返回。如果它是一个字符串,则可以使用.ToString()。如果是另一种类型,则需要使用System.Convert进行转换。

SqlDataReader rdr = cmd.ExecuteReader(); 
while (rdr.Read()) 
{ 
string column = rdr["ColumnName"].ToString(); 
int columnValue = Convert.ToInt32(rdr["ColumnName"]); 
} 
1

您可以在while while循环内使用dr.Read()。像这样:

while(dr.read()) 
{ 
    // MessageBox.Show("loginSuccess");  
} 
相关问题