Skip to content

Instantly share code, notes, and snippets.

@SleepyCrat
Created September 2, 2015 20:12
Show Gist options
  • Save SleepyCrat/26b7e7d2b9f87bb29f26 to your computer and use it in GitHub Desktop.
Save SleepyCrat/26b7e7d2b9f87bb29f26 to your computer and use it in GitHub Desktop.
A quick and dirty way to take a sql statement and get a datatable, a dictionary of Jobjects, an ennumeration of jojects, or the json string for a set of data without having to be too concerned with a bunch of column management.
//nuget Newtonsoft.Json <--Get this guy from nuget
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace GistCollection
{
public class JSONAndSQLManipulation
{
public DataTable GetDataTable(string query, string connectionString)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
DataTable theTable = new DataTable();
try
{
cmd.Connection.Open();
theTable.Load(cmd.ExecuteReader());
}
finally
{
if (cmd.Connection != null && cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
}
return theTable;
}
public Dictionary<string, JObject> GetJObjectDictionary(string keyName, string query, string connectionString)
{
var theTable = GetDataTable(query, connectionString);
var theDictionaryToReturn = new Dictionary<string, JObject>();
foreach (System.Data.DataRow dr in theTable.Rows)
{
var row = new JObject();
foreach (System.Data.DataColumn col in theTable.Columns)
{
row.Add(col.ColumnName.Trim(), JToken.FromObject(dr[col]));
}
theDictionaryToReturn.Add((string)row[keyName], row);
}
return theDictionaryToReturn;
}
public IEnumerable<JObject> GetJObjectDictionary(string query, string connectionString)
{
var theTable = GetDataTable(query, connectionString);
var theReturn = new List<JObject>();
foreach (System.Data.DataRow dr in theTable.Rows)
{
var row = new JObject();
foreach (System.Data.DataColumn col in theTable.Columns)
{
row.Add(col.ColumnName.Trim(), JToken.FromObject(dr[col]));
}
theReturn.Add(row);
}
return theReturn;
}
public string GetJObjectDictionaryJson(string query, string connectionString)
{
return JsonConvert.SerializeObject(GetJObjectDictionary(query, connectionString));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment