You are on page 1of 2

using

using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Data.SqlClient;
System.Data;

namespace BCP_tried.DataBase
{
class DataBase
{
private static string getStringConnection()
{
SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder();
stringBuilder.DataSource = @"(localdb)\Projects";
stringBuilder.InitialCatalog = "BCP-tried";
stringBuilder.IntegratedSecurity = true;
return stringBuilder.ConnectionString;
}
public static async Task<List<T>> sqlQuery<T>(string query, List<SqlParameter> Sqlparameters) where T : new()
{
List<T> rows = null;
using (SqlConnection sqlConnection = new SqlConnection(getStringConnection()))
{
using(SqlCommand command = new SqlCommand(query, sqlConnection))
{
command.Parameters.AddRange(Sqlparameters.ToArray());
sqlConnection.Open();
SqlDataReader reader = await command.ExecuteReaderAsync();
rows = Util.SqlReaderToObject<T>(reader);
sqlConnection.Close();
}
}
return rows;
}
public static async Task<bool> sqlNonQuery(string query, List<SqlParameter> Sqlparameters)
{
int rows=-1;
bool response;
using (SqlConnection sqlConnection = new SqlConnection(getStringConnection()))
{
using (SqlCommand command = new SqlCommand(query, sqlConnection))
{
command.Parameters.AddRange(Sqlparameters.ToArray());
try
{
sqlConnection.Open();
rows = await command.ExecuteNonQueryAsync();
sqlConnection.Close();
response = true;
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
response = false;
}
}
}
System.Diagnostics.Debug.WriteLine(string.Format("FILAS AFECTADAS: {0}",rows));
return response;
}
}
}

using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Data.SqlClient;
System.Linq;
System.Reflection;
System.Text;
System.Threading.Tasks;

namespace BCP_tried
{
class Util
{
public static List<T> SqlReaderToObject<T>(SqlDataReader reader) where T : new()
{
List<T> listObjects = new List<T>();
T myObject;
while (reader.Read())
{
myObject = new T();
foreach (PropertyInfo property in myObject.GetType().GetProperties())
{
if (reader[property.Name] != DBNull.Value)
{
property.SetValue(myObject, Convert.ChangeType(reader[property.Name], property.PropertyType, null));
}
}
listObjects.Add(myObject);
System.Diagnostics.Debug.WriteLine("USER: " + myObject);
}
return listObjects;
}
public static List<object[]> SqlReaderToList(SqlDataReader reader)
{
object[] row;
List<object[]> rows = new List<object[]>();
while (reader.Read())
{
row = new object[reader.FieldCount];
reader.GetValues(row);
rows.Add(row);
}
return rows;
}
}
}

You might also like