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>
Code description:
using
statement ensures that the SqlDataReader resource is released correctly. while
loop, the rdr.Read()
method moves the reader to the next row of data in the result set. rdr.GetString(0)
method retrieves a string value from the first column of the current row. 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!