Home >Backend Development >C++ >How to Read String Values from a SQLDataReader in C#?
Extracting String Data from a SQLDataReader in C#
C# developers frequently interact with SQL databases, retrieving data through commands and processing the results. The ExecuteReader()
method is a common approach, returning a SqlDataReader
object to navigate query results row by row and access individual columns.
Let's say you're working with a SQL Server database (e.g., SQL Server 2008) containing a table with a string column. This example shows how to read these strings using C# and ASP.NET.
The following code snippet illustrates retrieving string values from a SqlDataReader
:
<code class="language-csharp">using (SqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { string myString = rdr.GetString(0); // Accesses the first column (index 0) //Further processing of the string, such as adding to a list: myStringList.Add(myString); } }</code>
This code utilizes a using
statement for proper resource management, ensuring the SqlDataReader
is closed and disposed of automatically. ExecuteReader()
executes the SQL command and provides the SqlDataReader
.
The rdr.Read()
method moves the cursor to the next row. It returns false
when no more rows exist.
rdr.GetString(0)
retrieves the string value from the first column (index 0). This process repeats for each row, allowing you to collect and process the string data as required (e.g., adding to a list for later use).
The above is the detailed content of How to Read String Values from a SQLDataReader in C#?. For more information, please follow other related articles on the PHP Chinese website!