简体   繁体   English

从 SqlDataReader 读取数据

[英]Read data from SqlDataReader

I have a SQL Server 2008 database and I am working on it in the backend.我有一个 SQL Server 2008 数据库,我正在后端处理它。 I am working on asp.net/C#我正在研究 asp.net/C#

SqlDataReader rdr = cmd.ExecuteReader();  
while (rdr.Read())  
{              
   //how do I read strings here????  
}  

I know that the reader has values.我知道读者有价值观。 My SQL command is to select just 1 column from a table.我的 SQL 命令是从表中只选择 1 列。 The column contains strings ONLY.该列仅包含字符串。 I want to read the strings (rows) in the reader one by one.我想一一读取阅读器中的字符串(行)。 How do I do this?我该怎么做?

using(SqlDataReader rdr = cmd.ExecuteReader())
{
    while (rdr.Read())
    {
        var myString = rdr.GetString(0); //The 0 stands for "the 0'th column", so the first column of the result.
        // Do somthing with this rows string, for example to put them in to a list
        listDeclaredElsewhere.Add(myString);
    }
}
string col1Value = rdr["ColumnOneName"].ToString();

or

string col1Value = rdr[0].ToString();

These are object s, so you need to either cast them or .ToString() .这些是object ,因此您需要.ToString()它们或.ToString()

Put the name of the column begin returned from the database where "ColumnName" is.将从"ColumnName"所在的数据库返回的列名放在开始处。 If it is a string, you can use .ToString() .如果是字符串,则可以使用.ToString() If it is another type, you need to convert it using System.Convert .如果是其他类型,则需要使用System.Convert进行转换。

SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    string column = rdr["ColumnName"].ToString();
    int columnValue = Convert.ToInt32(rdr["ColumnName"]);
}
while(rdr.Read())
{
   string col=rdr["colName"].ToString();
}

it wil work它会起作用

For a single result:对于单个结果:

if (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

For multiple results:对于多个结果:

while (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

Thought to share my helper method for those who can use it:想与那些可以使用它的人分享我的帮助方法:

public static class Sql
{
    public static T Read<T>(DbDataReader DataReader, string FieldName)
    {
        int FieldIndex;
        try { FieldIndex = DataReader.GetOrdinal(FieldName); }
        catch { return default(T); }

        if (DataReader.IsDBNull(FieldIndex))
        {
            return default(T);
        }
        else
        {
            object readData = DataReader.GetValue(FieldIndex);
            if (readData is T)
            {
                return (T)readData;
            }
            else
            {
                try
                {
                    return (T)Convert.ChangeType(readData, typeof(T));
                }
                catch (InvalidCastException)
                {
                    return default(T);
                }
            }
        }
    }
}

Usage:用法:

cmd.CommandText = @"SELECT DISTINCT [SoftwareCode00], [MachineID] 
                    FROM [CM_S01].[dbo].[INSTALLED_SOFTWARE_DATA]";
using (SqlDataReader data = cmd.ExecuteReader())
{
    while (data.Read())
    {
        usedBy.Add(
            Sql.Read<String>(data, "SoftwareCode00"), 
            Sql.Read<Int32>(data, "MachineID"));
    }
}

The helper method casts to any value you like, if it can't cast or the database value is NULL, the result will be null.辅助方法可以强制转换为您喜欢的任何值,如果不能强制转换或数据库值为 NULL,则结果将为空。

Actually, I figured it out myself that I could do this:实际上,我自己发现我可以这样做:

while (rdr.read())
{  
  string str = rdr.GetValue().ToString().Trim();  
}

I would argue against using SqlDataReader here;反对在这里使用SqlDataReader ADO.NET has lots of edge cases and complications, and in my experience most manually written ADO.NET code is broken in at least one way (usually subtle and contextual). ADO.NET 有很多边缘情况和复杂性,根据我的经验,大多数手动编写的 ADO.NET 代码至少在一种情况下(通常是微妙的和上下文)被破坏。

Tools exist to avoid this.有工具可以避免这种情况。 For example, in the case here you want to read a column of strings.例如,在这里您想读取一列字符串。 Dapper makes that completely painless: Dapper使这完全无痛:

var region = ... // some filter
var vals = connection.Query<string>(
    "select Name from Table where Region=@region", // query
    new { region } // parameters
).AsList();

Dapper here is dealing with all the parameterization, execution, and row processing - and a lot of other grungy details of ADO.NET.这里的 Dapper 正在处理所有参数化、执行和行处理 - 以及 ADO.NET 的许多其他肮脏的细节。 The <string> can be replaced with <SomeType> to materialize entire rows into objects. <string>可以替换为<SomeType>以将整行具体化为对象。

I know this is kind of old but if you are reading the contents of a SqlDataReader into a class, then this will be very handy.我知道这有点旧,但是如果您将 SqlDataReader 的内容读入一个类,那么这将非常方便。 the column names of reader and class should be same reader 和 class 的列名应该相同

public static List<T> Fill<T>(this SqlDataReader reader) where T : new()
        {
            List<T> res = new List<T>();
            while (reader.Read())
            {
                T t = new T();
                for (int inc = 0; inc < reader.FieldCount; inc++)
                {
                    Type type = t.GetType();
                    string name = reader.GetName(inc);
                    PropertyInfo prop = type.GetProperty(name);
                    if (prop != null)
                    {
                        if (name == prop.Name)
                        {
                            var value = reader.GetValue(inc);
                            if (value != DBNull.Value)
                            { 
                                prop.SetValue(t, Convert.ChangeType(value, prop.PropertyType), null);
                            }
                            //prop.SetValue(t, value, null);

                        }
                    }
                }
                res.Add(t);
            }
            reader.Close();

            return res;
        }

In the simplest terms, if your query returns column_name and it holds a string:用最简单的术语来说,如果您的查询返回 column_name 并且它包含一个字符串:

while (rdr.Read())
{
    string yourString = rdr.getString("column_name")
}

I usually read data by data reader this way.我通常通过这种方式通过数据读取器读取数据。 just added a small example.刚刚添加了一个小例子。

string connectionString = "Data Source=DESKTOP-2EV7CF4;Initial Catalog=TestDB;User ID=sa;Password=tintin11#";
string queryString = "Select * from EMP";

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
                        }
                    }
                    reader.Close();
                }
            }

I have a helper function like:我有一个辅助功能,如:

  public static string GetString(object o)
    {
        if (o == DBNull.Value)
            return "";

        return o.ToString();
    }

then I use it to extract the string:然后我用它来提取字符串:

 tbUserName.Text = GetString(reader["UserName"]);

You have to read database column here.您必须在此处read database column You could have a look on following code snippet您可以查看以下代码片段

                string connectionString = ConfigurationManager.ConnectionStrings["NameOfYourSqlConnectionString"].ConnectionString;
                using (var _connection = new SqlConnection(connectionString))
                {
                    _connection.Open();

                    using (SqlCommand command = new SqlCommand("SELECT SomeColumnName FROM TableName", _connection))
                    {

                        SqlDataReader sqlDataReader = command.ExecuteReader();
                        if (sqlDataReader.HasRows)
                        {
                            while (sqlDataReader.Read())
                            {
                                string YourFirstDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
                                string YourSecondDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
                                string YourThridDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();

                            }
                        }
                        sqlDataReader.Close();
                    }
                    _connection.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM