Ralph
Ralph

Reputation: 1

Information retreival from sql server database

I want to retreive customer information from microsoft sql server database using just his/her user id onto a web form, can i get some help with this.

Upvotes: 0

Views: 161

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

You could start by writing a class which will define what a customer is:

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

Then a method to retrieve this customer from the database:

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

and finally call this function in your web form:

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

And if you want to avoid writing SQL queries in your code you could use an ORM such as the Entity Framework.

Upvotes: 1

Related Questions