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
Release: 2024-12-27 08:48:11
Original
593 people have browsed it

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");
Copy after login

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);
Copy after login

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);
Copy after login

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

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

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

public class Person
{
    public string firstName;
    public string lastName;
}
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template