Skip to content

Instantly share code, notes, and snippets.

@mrtank
Created February 9, 2018 13:56
Show Gist options
  • Save mrtank/7d47685fa2cf91966d57e3a0bed7be88 to your computer and use it in GitHub Desktop.
Save mrtank/7d47685fa2cf91966d57e3a0bed7be88 to your computer and use it in GitHub Desktop.
namespace SqlStuff
{
using System.Data.SqlClient;
using System;
using System.Collections.Generic;
public class Class1: IDisposable
{
private readonly SqlConnection connection = new SqlConnection("Data Source=garai;Initial Catalog=testChina;Integrated Security=True");
public Class1()
{
connection.Open();
}
public IEnumerable<IDictionary<String, Object>> ReadStuff()
{
string query = "SELECT * FROM dbo.test";
using (var command = new SqlCommand(query, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return ReadAsDictionary(reader);
}
}
}
private IDictionary<String, Object> ReadAsDictionary(SqlDataReader reader)
{
IDictionary<String, Object> dataRecord = new Dictionary<String, Object>();
for (var i = 0; i < reader.FieldCount; i++)
{
dataRecord.Add(reader.GetName(i), reader.GetValue(i));
}
return dataRecord;
}
public void Dispose()
{
connection?.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment