Read data from DB generic function - c#

I am new to working in dot net. What I am trying to do is create a helper method which will fetch data from DB for any table. I have passed parameters dynamically it working fine. But when I try to read the data, I am finding it difficult to store the data in some collection. This I will be returning back to my calling point and bind it to a response type and return.
public static Dictionary<Dictionary<string, object>, object> GetData(SqlCommand cmd, string connectionString, List<SqlParameter> parameters)
{
try
{
SqlDataReader reader = null;
Dictionary<Dictionary<string,object>, object> returnObjects = new Dictionary<Dictionary<string, object>, object>();
Dictionary<string, object> returnObject = new Dictionary<string, object>();
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
cmd.Connection = sqlConnection;
cmd.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
returnObject.Add(reader.GetName(i), reader[i]);
}
returnObject.Clear();
returnObjects.Add(returnObject, reader);
}
}
}
return returnObjects;
}
catch (Exception ex)
{
throw;
}
}
In above code when i try to add in returnObjects dictionary it says key already added. Below is the code from where I am calling and patientResponse where I want to return.
Dictionary<Dictionary<string, object>, object> dct = new Dictionary<Dictionary<string, object>, object>();
dct = Helper.GetData(cmd, connectionString, parameters);
List<Patient_Response> pp = new List<Patient_Response>();
Patient_Response pr = new Patient_Response();
pr.Patient_Id = int.Parse(reader["ID"].ToString());
pr.FIRST_NAME = reader["FIRST_NAME"].ToString();
pr.LAST_NAME = reader["LAST_NAME"].ToString();
pr.phoneNumber = reader["TEL"].ToString();
pr.email = reader["EMAIL"].ToString();
pr.Address = reader["Address"].ToString();
pr.Gender = reader["Gender"].ToString();
pr.DOB = Convert.ToDateTime(reader["DOB"]).ToString("MM/dd/yyyy");
pp.Add(pr);
What i can use instead of dictionary so that i can get a collection returned.

What surely doesn't work in your code is that you add the same instance of returnObject for each row. You should put new Dictionary<string, object>() inside the while. Also, if your result set contains duplicate field names, you'll get an exception.
public static List<Dictionary<string, object>> GetData(SqlCommand cmd, string connectionString, List<SqlParameter> parameters)
{
try
{
SqlDataReader reader = null;
// changed this to be a list
List<Dictionary<string,object>> returnObjects = new List<Dictionary<string, object>>();
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
cmd.Connection = sqlConnection;
cmd.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
// create a new returnObject for each row
Dictionary<string, object> returnObject = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
// following line throws an exception if there are multiple fields with the same name
returnObject.Add(reader.GetName(i), reader[i]);
}
returnObjects.Add(returnObject);
}
}
}
return returnObjects;
}
catch (Exception ex)
{
throw;
}
}
That said, there is not much benefit from first putting the content of reader into a list of dictionaries and then into a list of Patient_Response. You might as well directly fill a List<Patient_Response> from the reader (i.e. inside the while).
A generic way to do this might be (code is not verified to compile or run):
public static List<T> GetData<T>(
SqlCommand cmd,
string connectionString,
List<SqlParameter> parameters,
Func<IDataReader, T> readerToRow)
{
List<T> returnObjects = new List<T>();
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
cmd.Connection = sqlConnection;
cmd.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
returnObjects.Add(readerToRow(reader));
}
}
return returnObjects;
}
// To call above function:
List<Patient_Response> pp = Helper.GetData(
cmd,
connectionString,
parameters,
reader =>
new Patient_Response
{
FIRST_NAME = reader["FIRST_NAME"].ToString(),
LAST_NAME = reader["LAST_NAME"].ToString(),
// more columns go here
}
);

Related

Access multiple tables returned by stored procedure [duplicate]

Can I execute multiple queries and return their results executing a SqlCommand just once?
See SqlDataReader.NextResult (an SqlDataReader is returned from calling SqlCommand.ExecuteReader):
Advances the data reader to the next result [set], when reading the results of batch Transact-SQL statements.
Example:
string commandText = #"SELECT Id, ContactId
FROM dbo.Subscriptions;
SELECT Id, [Name]
FROM dbo.Contacts;";
List<Subscription> subscriptions = new List<Subscription>();
List<Contact> contacts = new List<Contact>();
using (SqlConnection dbConnection = new SqlConnection(#"Data Source=server;Database=database;Integrated Security=true;"))
{
dbConnection.Open();
using (SqlCommand dbCommand = dbConnection.CreateCommand())
{
dbCommand.CommandText = commandText;
using(SqlDataReader reader = dbCommand.ExecuteReader())
{
while(reader.Read())
{
subscriptions.Add(new Subscription()
{
Id = (int)reader["Id"],
ContactId = (int)reader["ContactId"]
});
}
// this advances to the next resultset
reader.NextResult();
while(reader.Read())
{
contacts.Add(new Contact()
{
Id = (int)reader["Id"],
Name = (string)reader["Name"]
});
}
}
}
}
Other examples:
C# Multiple Result Sets
Executing a Query That Returns Multiple Result Sets with SqlDataReader : SqlCommand Select « ADO.Net « C# / CSharp Tutorial
Create a Stored Procedure that has multiple selects, and fill the DataSet.
using (SqlConnection conn = new SqlConnection(connection))
{
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("MyProcedure", conn);
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.Fill(dataset);
return dataset;
}
The returned dataset will have a DataTable in it's Tables array for each select in the stored procedure.
Tools like "dapper" make this very easy, regardless of whether you use ad-hoc text queries or stored procedures; for example:
using(var multi = conn.QueryMultiple(sql, args))
{
var customers = multi.Read<Customer>().AsList(); // first grid
var regionName = multi.ReadFirstOrDefault<string>(); // second grid
var addresses = multi.Read<Address>().AsList(); // third grid
// todo: use those things
}
Individual grids can also be read without buffering (as an open IEnumerable<T> over the reader itself) via the optional parameters to Read[<T>].
I am using a dictionary approach.
You can use Newton Json to convert it to json.
This way you are not tied to types and IDataRecord
public List<List<Dictionary<string, object>>> ExecuteSqlReader(string cmd, int commandTimeout = 30, CommandType commandType = CommandType.Text)
{
var sqlCmd = new SqlCommand(cmd);
var allRecord = new List<List<Dictionary<string, object>>>();
using (var connection = GetSqlConnection(commandTimeout, commandType, ref sqlCmd))
{
using (var reader = sqlCmd.ExecuteReader())
{
if (reader.HasRows)
{
var result = new List<Dictionary<string, object>>();
while (reader.Read())
{
result = GetTableRowData(reader);
}
allRecord.Add(result);
}
while (reader.NextResult())
{
if (reader.HasRows)
{
var result = new List<Dictionary<string, object>>();
while (reader.Read())
{
result = GetTableRowData(reader);
}
allRecord.Add(result);
}
}
}
}
return allRecord;
}
I call a sproc and get multiple result sets with object, so you end up with a
List<List<Dictionary<string, object>>>
In the multiResultsSet each results set is then
List<Dictionary<string, object>>
They can be cast to their types and transformed into the models as needed.
After you set up the sproc command with everything needed, pass it to this:
private static List<List<Dictionary<string, object>>> ProcessReader(SqlCommand command)
{
var tables = new List<List<Dictionary<string, object>>>();
using (var reader = command.ExecuteReader())
{
do
{
var table = new List<Dictionary<string, object>>();
while (reader.Read())
table.Add(Read(reader));
tables.Add(table);
} while (reader.NextResult());
}
return tables;
}
and Read() is fairly straight forward.
private static Dictionary<string, object> Read(IDataRecord reader)
{
var row = new Dictionary<string, object>();
for (var i = 0; i < reader.FieldCount; i++)
{
var val = reader[i];
row[reader.GetName(i)] = val == DBNull.Value ? null : val;
}
return row;
}
This is what i have been using for returning multiple result sets.
public abstract class BaseRepo
{
private string _connectionString;
protected BaseRepo(string connectionString)
{
_connectionString = connectionString;
}
private SqlConnection GetSqlConnection(int commandTimeout, CommandType commandType, ref SqlCommand sqlCmd)
{
var connection = new SqlConnection(_connectionString);
connection.Open();
sqlCmd.Connection = connection;
sqlCmd.CommandTimeout = commandTimeout;
sqlCmd.CommandType = commandType;
return connection;
}
protected int ExecuteSql(SqlCommand sqlCmd, int commandTimeout = 30, CommandType commandType = CommandType.Text)
{
using (var connection = GetSqlConnection(commandTimeout, commandType, ref sqlCmd))
{
return sqlCmd.ExecuteNonQuery();
}
}
protected IEnumerable<T> ExecuteSqlReader<T>(Func<IDataRecord, T> CreateObject, SqlCommand sqlCmd, int commandTimeout = 30, CommandType commandType = CommandType.Text)
{
using (var connection = GetSqlConnection(commandTimeout, commandType, ref sqlCmd))
{
using (var reader = sqlCmd.ExecuteReader())
return ExecuteReader(CreateObject, reader);
}
}
protected Tuple<IEnumerable<T1>, IEnumerable<T2>> ExecuteSqlReader<T1,T2>(Func<IDataRecord, T1> CreateObject1, Func<IDataRecord, T2> CreateObject2, SqlCommand sqlCmd, int commandTimeout = 30, CommandType commandType = CommandType.Text)
{
using (var connection = GetSqlConnection(commandTimeout, commandType, ref sqlCmd))
{
using (var reader = sqlCmd.ExecuteReader())
{
var result1 = ExecuteReader(CreateObject1, reader).ToList();
var result2 = ExecuteReader(CreateObject2, reader).ToList();
return Tuple.Create<IEnumerable<T1>, IEnumerable<T2>>(result1, result2);
}
}
}
protected Tuple<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>> ExecuteSqlReader<T1, T2, T3>(Func<IDataRecord, T1> CreateObject1, Func<IDataRecord, T2> CreateObject2, Func<IDataRecord, T3> CreateObject3, SqlCommand sqlCmd, int commandTimeout = 30, CommandType commandType = CommandType.Text)
{
using (var connection = GetSqlConnection(commandTimeout, commandType, ref sqlCmd))
{
using (var reader = sqlCmd.ExecuteReader())
{
var result1 = ExecuteReader(CreateObject1, reader).ToList();
var result2 = ExecuteReader(CreateObject2, reader).ToList();
var result3 = ExecuteReader(CreateObject3, reader).ToList();
return Tuple.Create<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>>(result1, result2, result3);
}
}
}
protected Tuple<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>, IEnumerable<T4>> ExecuteSqlReader<T1, T2, T3, T4>(Func<IDataRecord, T1> CreateObject1, Func<IDataRecord, T2> CreateObject2, Func<IDataRecord, T3> CreateObject3, Func<IDataRecord, T4> CreateObject4, SqlCommand sqlCmd, int commandTimeout = 30, CommandType commandType = CommandType.Text)
{
using (var connection = GetSqlConnection(commandTimeout, commandType, ref sqlCmd))
{
using (var reader = sqlCmd.ExecuteReader())
{
var result1 = ExecuteReader(CreateObject1, reader).ToList();
var result2 = ExecuteReader(CreateObject2, reader).ToList();
var result3 = ExecuteReader(CreateObject3, reader).ToList();
var result4 = ExecuteReader(CreateObject4, reader).ToList();
return Tuple.Create<IEnumerable<T1>, IEnumerable<T2>, IEnumerable<T3>, IEnumerable<T4>>(result1, result2, result3, result4);
}
}
}
private IEnumerable<T> ExecuteReader<T>(Func<IDataRecord, T> CreateObject, SqlDataReader reader)
{
while (reader.Read())
{
yield return CreateObject(reader);
}
reader.NextResult();
}
}
Then I just inherit it like so:
public class ReviewRepo : BaseRepo
{
public ReviewRepo(string connectionString) : base(connectionString) { }
public ReviewPageableResult GetAllReviews(string productType, string serviceType, int pageNumber, int itemsPerPage, string sortBy, string sortDirection)
{
var parameters = new List<SqlParameter>
{
new SqlParameter("ProductRefDescription", productType),
new SqlParameter("ServiceRefDescription", serviceType),
new SqlParameter("ZipCodes", "NULL"),
new SqlParameter("PageNumber", pageNumber),
new SqlParameter("ItemsPerPage", itemsPerPage),
new SqlParameter("SortBy", sortBy),
new SqlParameter("SortDirection", sortDirection)
};
var cmd = new SqlCommand("dbo.GetReviews");
cmd.Parameters.AddRange(parameters.ToArray());
var results = ExecuteSqlReader(CreateReview, CreateReviewPageableResult, cmd, commandType: CommandType.StoredProcedure);
var reviewResult = results.Item2.Single();
reviewResult.Items = results.Item1;
return reviewResult;
}
public ReviewPageableResult GetReviewsByZip(string productType, string serviceType, string zipCodes, int pageNumber, int itemsPerPage, string sortBy, string sortDirection)
{
var parameters = new List<SqlParameter>
{
new SqlParameter("ProductRefDescription", productType),
new SqlParameter("ServiceRefDescription", serviceType),
new SqlParameter("ZipCodes", zipCodes),
new SqlParameter("PageNumber", pageNumber),
new SqlParameter("ItemsPerPage", itemsPerPage),
new SqlParameter("SortBy", sortBy),
new SqlParameter("SortDirection", sortDirection)
};
var cmd = new SqlCommand("dbo.GetReviewsByZipCodes");
cmd.Parameters.AddRange(parameters.ToArray());
var results = ExecuteSqlReader(CreateReview, CreateReviewPageableResult, cmd, commandType: CommandType.StoredProcedure);
var reviewResult = results.Item2.Single();
reviewResult.Items = results.Item1;
return reviewResult;
}
private Review CreateReview(IDataRecord record)
{
return new Review
{
PageReviewId = (int)record["PageReviewId"],
ProductRefId = (Guid)record["ProductRefId"],
ServiceTypeRefId = Convert.IsDBNull(record["ServiceTypeRefId"]) ? Guid.Empty : (Guid)record["ServiceTypeRefId"],
TerritoryId = Convert.IsDBNull(record["TerritoryId"]) ? Guid.Empty : (Guid)record["TerritoryId"],
FirstName = $"{record["FirstName"]}",
LastName = $"{record["LastName"]}",
City = $"{record["City"]}",
State = $"{record["State"]}",
Answer = $"{record["Answer"]}",
Rating =(double)record["Rating"],
SurveyDate = (DateTime)record["SurveyDate"]
};
}
private ReviewPageableResult CreateReviewPageableResult(IDataRecord record)
{
return new ReviewPageableResult
{
AverageRating = (double)record["AverageRating"],
Count1Stars = (int)record["Count1Stars"],
Count2Stars = (int)record["Count2Stars"],
Count3Stars = (int)record["Count3Stars"],
Count4Stars = (int)record["Count4Stars"],
Count5Stars = (int)record["Count5Stars"],
ItemsPerPage = (int)record["ItemsPerPage"],
PageNumber = (int)record["PageNumber"],
TotalCount = (int)record["TotalCount"],
};
}
}
Try this
Dim dt1, dt2, dt3As New DataTable
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim Sql1, Sql2, Sql3 As String
Sql1 = "select id, CurName from Table1 where IS_Deleted=0 order by id"
Sql2 = "select id ,Item from Table2 order by id"
Sql3 = "select id ,SellPrice from Table3 order by id"
Try
conn1.Open()
command = New SqlCommand(Sql1, conn1)
command.CommandType = CommandType.Text
adapter.SelectCommand = command
adapter.Fill(ds, "dt1")
adapter.SelectCommand.CommandText = Sql2
adapter.Fill(ds, "dt2")
adapter.SelectCommand.CommandText = Sql3
adapter.Fill(ds, "dt3")
adapter.Dispose()
command.Dispose()
conn1.Close()
cmbCurrency.DataSource = ds.Tables("dt1")
cmbCurrency.DisplayMember = "CurName"
cmbCurrency.ValueMember = "id"
cmbCurrency.SelectedIndex = -1
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''|
cmbGroups.DataSource = ds.Tables("dt2")
cmbGroups.DisplayMember = "Item"
cmbGroups.ValueMember = "id"
cmbGroups.SelectedIndex = -1
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''|
cmbUnits.DataSource = ds.Tables("dt3")
cmbUnits.DisplayMember = "SellPrice"
cmbUnits.ValueMember = "id"
cmbUnits.SelectedIndex = -1
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''|
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
For More Help http://vb.net-informations.com/dataset/dataset-multiple-tables-sqlserver.htm

Read data from SQL Server with dictionary in C#

var query = "SELECT OrderNo, PlannedQuantity, CompletedQuantity, IsClosed" +
" FROM Order1 WHERE OrderNo =:orderNo";
var arguments = new Dictionary<string, object>() { { "orderNo", orderNo } };
using (var reader = ExecuteDatabaseReader(query, arguments))
{
if (reader.Read())
{
return GetOrderFromReader(reader);
}
}
static IDataReader ExecuteDatabaseReader(string query, IDictionary<string, object> arguments)
{
return null;
}
You should implement a method like below. Of cource code below is a simple code and it needs to be very better. For example, I haven't managed to close and dispose the connection.
static IDataReader ExecuteDatabaseReader(string query, IDictionary < string, object > arguments) {
var conn = new SqlConnection(your_connection_string);
conn.Open();
var commadn = conn.CreateCommand();
command.CommandText = query;
foreach(var key in arguments.Keys) {
command.Parameters.AddWithValue(key, arguments[key]);
}
return command.ExecuteReader();
}
One important notes about parameters, I don't know what your RDBMS is if it's SQL Server you need to define your parameters with # sign.
var dictionary = new Dictionary<string, object>();
dictionary.Add("#Id", 1);
dictionary.Add("#Name", "Name");

Does my code close connection to SQL Server

So method GetAllData is one of my universal methods for connecting to the database and here, since I have to add mupltiple records in once to the database I need to have one connetion with multiple commands to run. So my question is does this way of connection closes the database correctly, or if you have any improvments to my code please share with me.
var conn = new SqlConnection(ConnString);
conn.Open();
var data = new Dictionary<string, List<object>>();
foreach (var h in hours)
{
data += SqlUniversal.GetAllData(query,//idk how I will collect the data yet... i know += wouldnt work for dictionary
new[] {
//some parameters
},
conn);
}
//Here is the method, above is how I call it.
public static Dictionary<string, List<object>> GetAllData(string command, SqlParameter[] pars, SqlConnection conn)
{
if (conn == null)
{
conn = new SqlConnection(ConnString);
conn.Open();
}
var res = new Dictionary<string, List<object>>();
using (conn)
{
using (var cmd = new SqlCommand(command, conn))
{
cmd.Parameters.AddRange(pars);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
for (var i = 0; i < reader.VisibleFieldCount; i++)
{
if (reader.GetValue(i) == DBNull.Value)
continue;
var name = reader.GetName(i);
if (res.ContainsKey(name))
res[name].Add(reader.GetValue(i));
else
res.Add(name, new List<object> {reader.GetValue(i)});
}
return res;
}
}
}
}
Probably the better way to do this is to let the overseeing method manage the connection:
public void SomeDataMethod()
{
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var data = new Dictionary<string, List<object>>();
foreach (var h in hours)
{
data += SqlUniversal.GetAllData(query,
new[] {
//some parameters
},
conn);
}
}
}
And remove the using (conn) from the GetData method:
public static Dictionary<string, List<object>> GetAllData(string command, SqlParameter[] pars, SqlConnection conn)
{
var res = new Dictionary<string, List<object>>();
using (var cmd = new SqlCommand(command, conn))
{
cmd.Parameters.AddRange(pars);
using (var reader = cmd.ExecuteReader())
{
//...
return res;
}
}
}
Now SomeDataMethod controls the connection lifetime and GetData doesn't worry about connection management.

Retrieving data from a database through SqlDataReader and converting it to JSON

I want to convert my retrieved data into JSON; I am using a SqlDataReader for retrieving. For that I need to store my data into var.
I am getting this error:
An exception of type 'System.Reflection.AmbiguousMatchException' occurred in mscorlib.dll but was not handled in user code
Additional information: Ambiguous match found.
in the following code:
public string GetDetails(int Id)
{
var jsonDoc = "";
string con = "server=FACULTY01\\SQLSERVER2012ENT; database=SampleDb; uid=sa; pwd=sa9";
SqlConnection scon = new SqlConnection(con);
string qry = "Select * from Information where ID =" + Id;
SqlCommand cmd = new SqlCommand(qry, scon);
scon.Open();
SqlDataReader rdr = cmd.ExecuteReader();
var details = rdr;
JavaScriptSerializer jss = new JavaScriptSerializer();
jsonDoc = jss.Serialize(details);
scon.Close();
return jsonDoc;
}
You can't directly serialize a SqlDataReader and expect the output to contain the data from the SQL query. That's not the way that SqlDataReader works. SqlDataReader is a means to retrieve data from the SQL result. You can use it to populate some other object (such as a Dictionary<string, object> or a strongly-typed class you define) which you can then hand to the serializer to produce JSON.
Try the code below instead. (Also note the use of using statements and parameterized SQL in keeping with good coding practices, as mentioned by #Jon Skeet.)
public static string GetDetails(int Id)
{
string con = "server=FACULTY01\\SQLSERVER2012ENT; database=SampleDb; uid=sa; pwd=sa9";
using (SqlConnection scon = new SqlConnection(con))
{
string qry = "Select * from Information where ID = #id";
SqlCommand cmd = new SqlCommand(qry, scon);
cmd.Parameters.AddWithValue("#id", Id);
scon.Open();
var details = new Dictionary<string, object>();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows && rdr.Read())
{
for (int i = 0; i < rdr.FieldCount; i++)
{
details.Add(rdr.GetName(i), rdr.IsDBNull(i) ? null : rdr.GetValue(i));
}
}
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsonDoc = jss.Serialize(details);
scon.Close();
return jsonDoc;
}
}
Note that the above code is expecting to get a single row back from the reader. If you are expecting more than one row then you will need to use another loop and put the resulting data into a List<Dictionary<string, object>> instead. Here is the part you would need to change:
...
var details = new List<Dictionary<string, object>>();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
var dict = new Dictionary<string, object>();
for (int i = 0; i < rdr.FieldCount; i++)
{
dict.Add(rdr.GetName(i), rdr.IsDBNull(i) ? null : rdr.GetValue(i));
}
details.Add(dict);
}
}
}
...
You need a loop to store the data from the reader. Use a DataTable to store the full table. A single variable will store single column data.
while (rdr.Read())
{
var details = rdr["columnName"];
}
Encountered this post as it comes first in google search.
Have given an answer here (based on this):
The requirement is somewhat similar that is of converting sqldatareader result to a json string.
public static class MyExtensions
{
public async static Task<string> toJSON(this SqlDataReader reader)
{
var results = await reader.GetSerialized();
return JsonConvert.SerializeObject(results, Formatting.Indented);
}
public async static Task<IEnumerable<Dictionary<string, object>>> GetSerialized(this 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 (await reader.ReadAsync())
results.Add(SerializeRow(cols, reader));
return results;
}
private static Dictionary<string, object> SerializeRow(IEnumerable<string> cols,
SqlDataReader reader)
{
var result = new Dictionary<string, object>();
foreach (var col in cols)
result.Add(col, reader[col]);
return result;
}
}
Use As :
var result = await reader.GetSerialized(); //to get the result object
or
string strResult = await reader.toJSON(); //to get the result string

Repeated SQL Connections, should I create a class?

I'm still quite new to c# and I have multiple count queries on a single page. I don't need to use these queries anywhere else so have avoided creating a class. Still though, I can help but think there must be a more efficient approach but I was wondering what that would be!
Here's an example
private void cntUp() {
Dictionary<string, string> crd = getCredentials(Session["secure"].ToString());
Label UserUpcoming = frmDash.FindControl("lblUserReviewUp") as Label;
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["CS"].ConnectionString))
{
con.Open();
try
{
using (SqlCommand countUpcoming = new SqlCommand("SELECT COUNT(*) FROM vw_dash_user_upcoming WHERE Employee_ID = #employee_id", con))
{
countUpcoming.Parameters.Add(new SqlParameter("employee_id", crd["employee_id"].ToString()));
SqlDataReader readerUpcoming = countUpcoming.ExecuteReader();
while (readerUpcoming.Read())
{
UserUpcoming.Text = readerUpcoming.GetInt32(0).ToString();
}
}
con.Close();
}
catch
{
Response.Redirect(this.ErrorPage);
}
}
}
The following Repository works with SQL Server.
Basically, you can either issue a regular or parameterized query.
You can pass in your parameters as all strings, or just as objects if you are going to use models with strongly typed numbers and dates.
You can take out the Release mode info if you don't use such a construct in developement, this is just to make it easier to switch between development and production databases without coding a change.
An example usage would be :
var updateStatement = "UPDATE OCCHistoryHeaders SET ValidatingUsername=#pUsername,ValidatingWorkstation=#pWorkstation,CurrentState = #pCurrentStatus,RejectionReason = #pRejectionReason, AutomatedValidation = '0' WHERE BatchId = #pBatchId";
var parameters = new Dictionary<string, object>
{
{"pUsername", Environment.UserName},
{"pWorkstation", Environment.MachineName},
{"pCurrentStatus", currentStatus},
{"pRejectionReason", rejectionReason},
{"pBatchId", batchId}
};
var absRowsUpdated = _occDb.ExecuteParameterizedNonQueryObjects(updateStatement, parameters);
Here is the class...
public class SomeRepository
{
private string _connectionString { get; set; }
private SqlConnection _sqlConnection { get; set; }
public SomeRepository()
{
switch (AppSettings.ReleaseMode)
{
case ReleaseMode.DEV:
_connectionString = "server=;database=;User Id=;Password=";
break;
case ReleaseMode.PRODUCTION:
_connectionString = "server=;database=;User Id=;Password=";
break;
}
}
public DataTable ExecuteQuery(string commandText)
{
var dataTable = new DataTable();
var _sqlConnection = new SqlConnection(_connectionString);
var cmd = new SqlCommand(commandText, _sqlConnection);
var da = new SqlDataAdapter(cmd);
try
{
_sqlConnection.Open();
da.Fill(dataTable);
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteQuery Error : QueryString={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
da.Dispose();
_sqlConnection.Dispose();
}
return dataTable;
}
public DataTable ExecuteParameterizedQuery(string commandText, Dictionary<string, string> parameters)
{
var dataTable = new DataTable();
var _sqlConnection = new SqlConnection(_connectionString);
var cmd = new SqlCommand(commandText, _sqlConnection);
var da = new SqlDataAdapter(cmd);
foreach (var entry in parameters)
{
cmd.Parameters.Add(entry.Key, entry.Value);
}
try
{
_sqlConnection.Open();
da.Fill(dataTable);
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteQuery Error : QueryString={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
da.Dispose();
_sqlConnection.Dispose();
}
return dataTable;
}
public DataTable ExecuteParameterizedQueryObjects(string commandText, Dictionary<string, object> parameters)
{
var dataTable = new DataTable();
var _sqlConnection = new SqlConnection(_connectionString);
var cmd = new SqlCommand(commandText, _sqlConnection);
var da = new SqlDataAdapter(cmd);
foreach (var entry in parameters)
{
cmd.Parameters.Add(entry.Key, entry.Value);
}
try
{
_sqlConnection.Open();
da.Fill(dataTable);
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteQuery Error : QueryString={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
da.Dispose();
_sqlConnection.Dispose();
}
return dataTable;
}
public int ExecuteNonQuery(string commandText)
{
var _sqlConnection = new SqlConnection(_connectionString);
var rowsAffected = 0;
try
{
var cmd = new SqlCommand(commandText, _sqlConnection);
_sqlConnection.Open();
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteNonQuery Error : Command={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
_sqlConnection.Dispose();
}
return rowsAffected;
}
public int ExecuteParameterizedNonQuery(string commandText, Dictionary<string, string> parameters)
{
var _sqlConnection = new SqlConnection(_connectionString);
var rowsAffected = 0;
var cmd = new SqlCommand(commandText, _sqlConnection);
foreach (var entry in parameters)
{
cmd.Parameters.Add(entry.Key, entry.Value);
}
try
{
_sqlConnection.Open();
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteNonQuery Error : Command={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
_sqlConnection.Dispose();
}
return rowsAffected;
}
public int ExecuteParameterizedNonQueryObjects(string commandText, Dictionary<string, object> parameters)
{
var _sqlConnection = new SqlConnection(_connectionString);
var rowsAffected = 0;
var cmd = new SqlCommand(commandText, _sqlConnection);
foreach (var entry in parameters)
{
cmd.Parameters.Add(entry.Key, entry.Value);
}
try
{
_sqlConnection.Open();
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
var errorText = string.Format("Occ Repository ExecuteNonQuery Error : Command={0} :: Error={1}", commandText, ex.Message);
throw new Exception(errorText, ex);
}
finally
{
_sqlConnection.Dispose();
}
return rowsAffected;
}
}
If you only do stuff 1 place, generally you'd make everything less readable. So I would probably avoid it. It's a common pattern, however, to you would do yourself a favor writing a utility class with some functions for this.
//requires query parameters to have names #0, #1 etc in string
public static List<object[]> Query(String query, params String[] parameters) //no injection check on this string, be careful.
{
using(SqlConnection conn = new SqlConnection(_CONN_STRING_))
{
conn.Open()
using(SqlCommand cmd = new SqlCommand(query, conn))
{
AddSqlParams(cmd, parameters);
return Query(cmd);
}
}
}
/// <summary>Generic SQL query. Requires open connection.</summary>
/// <param name="cmd">SqlCommand object with all necessary fields configured.</param>
/// <returns>A list of Object arrays (each array is one row).</returns>
private static List<Object[]> Query(SqlCommand cmd)
{
List<Object[]> results = new List<Object[]>();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Object[] row = new Object[rdr.VisibleFieldCount];
rdr.GetValues(row);
results.Add(row);
}
return results;
}
}
private static void AddSqlParams(SqlCommand cmd, params String[] sqlParams)
{
for (Int32 i = 0; i < sqlParams.Length; i++)
cmd.Parameters.AddWithValue("#" + i, (Object)sqlParams[i] ?? DBNull.Value);
}
Then use like
UserUpcoming.Text = Query("SELECT COUNT(*) FROM vw_dash_user_upcoming WHERE Employee_ID = #0", crd["employee_id"].ToString())[0][0];
I like to have a separate class for each table in the database. In your case I would have a separate class called vw_dash_user_upcoming, this would have a static method something like...
public static int CountEmployees(int employeeId) {
int returnValue;
// do database stuff here
return returnValue;
}
I usually create a folder and namespace in my project called "database" and all the database stuff goes in there. Nothing goes in there that's not database access. For me this really helps keep things organized, especially in a large project.
Personally I would create a separate class, simply because it's not a good idea to keep pieces of code with totally different responsibilities in one class. When divided into small classes code is easier to read and maintain.
Communication with database should be separated anyway to make it easier to switch between datasources (e.g. different database servers).

Categories