从sql server数据库中检索信息

时间:2011-05-09 07:42:16

标签: asp.net sql-server vb.net ado.net

我想从microsoft sql server数据库中使用他/她的用户ID检索客户信息到Web表单中,我可以得到一些帮助。

1 个答案:

答案 0 :(得分:1)

您可以从编写一个定义客户身份的类开始:

Public Class Customer
    Public Property Id As Integer
    Public Property FirstName As String
    Public Property LastName As String
End Class

然后是从数据库中检索此客户的方法:

Public Function GetCustomer(ByVal CustomerId As Integer) As Customer
    Using conn = New SqlConnection("Data Source=serverName;Initial Catalog=databaseName;User Id=username;Password=password;")
        Using cmd = conn.CreateCommand()
            conn.Open()
            cmd.CommandText = "SELECT id, first_name, last_name FROM customers WHERE id = @id"
            cmd.Parameters.AddWithValue("@id", CustomerId)
            Using reader = cmd.ExecuteReader()
                While reader.Read()
                    Dim Customer = New Customer()
                    Customer.Id = reader.GetInt32(reader.GetOrdinal("id"))
                    Customer.FirstName = reader.GetInt32(reader.GetOrdinal("first_name"))
                    Customer.LastName = reader.GetInt32(reader.GetOrdinal("last_name"))
                    Return Customer
                End While
            End Using
        End Using
    End Using
    Return Nothing
End Function

最后在您的网络表单中调用此函数:

Dim Customer = GetCustomer(123)
FirstNameTextBox.Text = Customer.FirstName
...

如果您想避免在代码中编写SQL查询,可以使用ORM,例如Entity Framework