当前位置: 代码迷 >> ASP.NET >> 请教大家这样做是否效率比较低下?如何样能判断SqlDataReader是否读取数据成功
  详细解决方案

请教大家这样做是否效率比较低下?如何样能判断SqlDataReader是否读取数据成功

热度:5624   发布时间:2013-02-25 00:00:00.0
请问大家这样做是否效率比较低下?怎么样能判断SqlDataReader是否读取数据成功?
Private Sub TestPhone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPhone.Click
  Locality.Text = ""
  Mycomponent.SqlCommand1.Parameters("@phone").Value = TboxPhone.Text
  Mycomponent.SqlConnection1.Open()
  Dim dr As SqlClient.SqlDataReader
  dr = Mycomponent.SqlCommand1.ExecuteReader
  While dr.Read()  
  Locality.Text = dr.GetString(1)
  Acreage.Text = dr.GetString(4)
  Price.Text = dr.GetString(5)
  LinkMan.Text = dr.GetString(6)
  Phone1.Text = dr.GetString(7)
  Phone2.Text = dr.GetString(8)
  Description.Text = dr.GetString(9)  
  End While
  dr.Close()
  Mycomponent.SqlConnection1.Close()
  If Locality.Text = "" Then
  Label1.Text = "不存在"
  Label1.Visible = True
  Else
  Label1.Visible = False
  Panel1.Visible = True
  End If
  End Sub

------解决方案--------------------------------------------------------
你的代码不是效率问题,而是潜在的数据库链接问题,维护的问题(sql代码与界面代码相混)

还有把While改成if

Private Sub TestPhone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPhone.Click 
Locality.Text = "" 

Try

Mycomponent.SqlCommand1.Parameters("@phone").Value = TboxPhone.Text 
Mycomponent.SqlConnection1.Open() 
Dim dr As SqlClient.SqlDataReader 
dr = Mycomponent.SqlCommand1.ExecuteReader 
if dr.Read()
Locality.Text = dr.GetString(1) 
Acreage.Text = dr.GetString(4) 
Price.Text = dr.GetString(5) 
LinkMan.Text = dr.GetString(6) 
Phone1.Text = dr.GetString(7) 
Phone2.Text = dr.GetString(8) 
Description.Text = dr.GetString(9)
End if
dr.Close() 

Finally
Mycomponent.SqlConnection1.Close() 
End Try


If Locality.Text = "" Then 
Label1.Text = "不存在" 
Label1.Visible = True 
Else 
Label1.Visible = False 
Panel1.Visible = True 
End If 
 End Sub

考虑把数据库访问逻辑移到另外的类去,返回一个数据实体