Home >Database >Mysql Tutorial >How to Retrieve Specific Data from a SQL Server Database Using C#?

How to Retrieve Specific Data from a SQL Server Database Using C#?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 12:56:11600browse

How to Retrieve Specific Data from a SQL Server Database Using C#?

Retrieve Data from a SQL Server Database in C#

When working with a database table containing columns such as firstname, Lastname, and age, retrieving specific data values based on user input can be essential. In this scenario, you have three textboxes in your C# Windows application and have established a connection to a SQL Server database.

To retrieve all other details corresponding to a given firstname value, a parametrized query approach is recommended for security reasons. Here's how you can achieve this:

public Person SomeMethod(string fName)
{
    var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();

    Person matchingPerson = new Person();
    using (SqlConnection myConnection = new SqlConnection(con))
    {
        string oString = "Select * from Employees where FirstName=@Fname";
        SqlCommand oCmd = new SqlCommand(oString, myConnection);
        oCmd.Parameters.AddWithValue("@Fname", fName);
        myConnection.Open();
        using (SqlDataReader oReader = oCmd.ExecuteReader())
        {
            while (oReader.Read())
            {
                matchingPerson.firstName = oReader["FirstName"].ToString();
                matchingPerson.lastName = oReader["LastName"].ToString();
            }

            myConnection.Close();
        }
    }
    return matchingPerson;
}

Explanation:

  1. We use a parametrized query ("Select * from Employees where FirstName=@fName") with a parameter named @fName to prevent SQL injection.
  2. We create a Person object to store the retrieved data.
  3. We execute the query, and if there is a matching record, we populate the Person object with the corresponding values (firstName and lastName).

Usage:

To use this method, you can call it like this:

Person x = SomeMethod("John");

Once you have the data in the Person object, you can assign the values to the textboxes in your application:

txtLastName.Text = x.LastName;

This approach allows you to retrieve all the other details related to a specific firstname value from the database and display them in the corresponding textboxes.

The above is the detailed content of How to Retrieve Specific Data from a SQL Server Database Using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn