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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 08:48:11668browse

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

Retrieving Data from a SQL Server Database in C#

Introduction
Accessing data from a database is a crucial task in software development. This article explores how to retrieve data from a SQL Server database using C#.

Database Connectivity
To connect to a SQL Server database, use the SqlConnection class:

SqlConnection con = new SqlConnection("connectionString");

Selecting Data
To select data from the database, use a SqlCommand with the Select * from tablename query:

SqlCommand cmd = new SqlCommand("Select * from tablename", con);

Dynamic SQL Query
To retrieve data based on a parameter, use a parameterized query to avoid SQL injection:

cmd.CommandText = "Select * from tablename where firstname = @fName";
cmd.Parameters.AddWithValue("@fName", textBox1.Text);

Reading Data
To read the retrieved data, use a SqlDataReader:

using (SqlDataReader oReader = oCmd.ExecuteReader())
{
    while (oReader.Read())
    {
        // Access column data...
    }
}

Custom Object
For cleaner code, define a custom object to represent the data:

public class Person
{
    public string firstName;
    public string lastName;
}

Populating TextBoxes
To populate textboxes with the retrieved data, use the properties of the custom object:

Person x = SomeMethod("John");
txtLastName.Text = x.lastName;

Conclusion
This article demonstrated how to retrieve data from a SQL Server database in C# using a parameterized query and a custom object, providing a flexible and secure approach to data access.

The above is the detailed content of How to Retrieve 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