Home > Backend Development > C++ > How to Extract Strings from a SqlDataReader in C#?

How to Extract Strings from a SqlDataReader in C#?

Patricia Arquette
Release: 2025-01-17 02:14:08
Original
357 people have browsed it

How to Extract Strings from a SqlDataReader in C#?

Get string data from SqlDataReader

When operating a SQL Server database in ASP.NET/C#, you may need to retrieve data from SqlDataReader. In particular, you may need to read string data from a specific column.

To do this, you can use the GetString() method of SqlDataReader. Consider the following code snippet:

<code class="language-csharp">using (SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        string myString = rdr.GetString(0); // 0 代表结果集的第 0 列(第一列)。
        // 对该行字符串进行操作,例如将其添加到列表中
        listDeclaredElsewhere.Add(myString);
    }
}</code>
Copy after login

Code description:

    The
  1. using statement ensures that the SqlDataReader resource is released correctly.
  2. Within the
  3. while loop, the rdr.Read() method moves the reader to the next row of data in the result set.
  4. The
  5. rdr.GetString(0) method retrieves a string value from the first column of the current row.
  6. You can then manipulate the string value as needed, such as adding it to a list.

Note that the column index specified in GetString() corresponds to the zero-based column index of the result set.

The above is the detailed content of How to Extract Strings from a SqlDataReader in 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