Visual Basic .NET从数据库读取字段
示例
Public Function GetUserFirstName(UserName As String) As String
Dim Firstname As String = ""
'Specify the SQL that you want to use including a Parameter
Dim SQL As String = "select firstname from users where username=@UserName"
'Provide a Data Source
Dim DBDSN As String = "Data Source=server.address;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserName;Password=UserPassword"
Dim dbConn As New SqlConnection(DBDSN)
Dim dbCommand As New SqlCommand(SQL, dbConn)
'Provide one or more Parameters
dbCommand.Parameters.AddWithValue("@UserName", UserName)
'An optional Timeout
dbCommand.CommandTimeout= 600
Dim reader As SqlDataReader
Dim previousConnectionState As ConnectionState = dbConn.State
Try
IfdbConn.State=ConnectionState.ClosedThen
dbConn.Open()
End If
reader = dbCommand.ExecuteReader
Using reader
With reader
If .HasRows Then
'Read the 1st Record
reader.Read()
'Read required field/s
Firstname = .Item("FirstName").ToString
End If
End With
End Using
Catch
'Handle the error here
Finally
If previousConnectionState =ConnectionState.ClosedThen
dbConn.Close()
End If
dbConn.Dispose()
dbCommand.Dispose()
End Try
'Pass the data back from the function
Return Firstname
End Function使用上面的函数很简单:
Dim UserFirstName as string=GetUserFirstName(UserName)
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短