Answers:
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();
要么
string col1Value = rdr[0].ToString();
这些是object
,因此您需要强制转换或.ToString()
。
while(rdr.Read())
{
string col=rdr["colName"].ToString();
}
它会工作
toString()
是无效的应该.ToString()
只是
对于单个结果:
if (reader.Read())
{
Response.Write(reader[0].ToString());
Response.Write(reader[1].ToString());
}
对于多个结果:
while (reader.Read())
{
Response.Write(reader[0].ToString());
Response.Write(reader[1].ToString());
}
想与那些可以使用它的人分享我的帮助方法:
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);
}
}
}
}
}
用法:
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"));
}
}
helper方法将强制转换为您喜欢的任何值,如果无法强制转换或数据库值为NULL,则结果将为null。
reader.GetColumn<int>("M_ID");
我知道这有点旧,但是如果您将SqlDataReader的内容读入一个类,那么这将非常方便。读者和班级的列名应该相同
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;
}
我反对SqlDataReader
在这里使用;ADO.NET具有许多极端情况和复杂性,以我的经验,大多数手动编写的ADO.NET代码至少以一种方式(通常是微妙的和上下文的)被破坏了。
有工具可以避免这种情况。例如,在这种情况下,您想读取一列字符串。Dapper使这一切变得无痛:
var region = ... // some filter
var vals = connection.Query<string>(
"select Name from Table where Region=@region", // query
new { region } // parameters
).AsList();
Dapper在这里处理所有的参数化,执行和行处理-以及ADO.NET的许多其他低俗的细节。该<string>
可以替换<SomeType>
到整个行兑现成对象。
用最简单的术语来说,如果您的查询返回column_name并且它包含一个字符串:
while (rdr.Read())
{
string yourString = rdr.getString("column_name")
}
我有一个辅助功能,如:
public static string GetString(object o)
{
if (o == DBNull.Value)
return "";
return o.ToString();
}
然后我用它来提取字符串:
tbUserName.Text = GetString(reader["UserName"]);
我通常以这种方式通过数据读取器读取数据。刚刚添加了一个小例子。
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();
}
}
你必须在read
database column
这里。您可以看一下以下代码片段
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();