What ‘length’ parameter should I pass to SqlDataReader.GetBytes()

When dealing with varbinary(max), there are two scenarios: the length of the data is moderate the length of the data is big GetBytes() is intended for the second scenario, when you are using CommandBehaviour.SequentialAccess to ensure that you are streaming the data, not buffering it. In particular, in this usage you would usually be writing … Read more

How to get nullable DateTime out of the database

A SQL null is not the same as a .NET null; you have to compare against System.DBNull.Value: object sqlDateTime = sqldatareader[0]; DateTime? dt = (sqlDateTime == System.DBNull.Value) ? (DateTime?)null : Convert.ToDateTime(sqlDateTime); In answer to your comment, the data type of the Item property of a DataReader is that of the underlying database type. It could … Read more

Multiples Table in DataReader

Try this because this will close connection ,data reader and command once task get over , so that this will not give datareader close exception Also do check like this if(reader.NextResult()) to check there is next result, using (SqlConnection connection = new SqlConnection(“connection string here”)) { using (SqlCommand command = new SqlCommand (“SELECT Column1 FROM … Read more

convert from SqlDataReader to JSON

If you want something that’ll convert to arbitrary JSON, you could convert by serializing it into a Dictionary(Of string, object) thusly: public IEnumerable<Dictionary<string, object>> Serialize(SqlDataReader reader) { var results = new List<Dictionary<string, object>>(); var cols = new List<string>(); for (var i = 0; i < reader.FieldCount; i++) cols.Add(reader.GetName(i)); while (reader.Read()) results.Add(SerializeRow(cols, reader)); return results; } … Read more

Check for column name in a SqlDataReader object

public static class DataRecordExtensions { public static bool HasColumn(this IDataRecord dr, string columnName) { for (int i=0; i < dr.FieldCount; i++) { if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase)) return true; } return false; } } Using Exceptions for control logic like in some other answers is considered bad practice and has performance costs. It also sends false positives … Read more

Read data from SqlDataReader

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); } }