简体   繁体   中英

Requesting databases with C#

I am wondering if the following code is an old approach for working with database. Or I can use more modern and productive approach?

using(SqlConnection con = new SqlConnection(Properties.Settings.Default.EventLogPrinterConnectionString))
{
    SqlCommand com = new SqlCommand("", con);

    string sql_com_sel = "";
    sql_com_sel = @"SELECT DISTINCT Users, Pages, Date FROM View_lastactiveUser WHERE (Date >= @ds AND Date <= @dp AND Pages > 0) ORDER BY Date";
    com.CommandText = sql_com_sel;
    com.Parameters.Clear();
    com.Parameters.Add("@ds", SqlDbType.DateTime).Value = ds;
    com.Parameters.Add("@dp", SqlDbType.DateTime).Value = dp;
    con.Open();
    SqlDataReader dr = com.ExecuteReader();
    while (dr.Read())
    {
        users.Add(new UserDemo() { LastActivity = dr["Date"].ToString(), Pages = int.Parse(dr["Pages"].ToString()), User = dr["Users"].ToString() });
    }
    con.Close();
    return users;
}

Using plain ADO.NET is still a very valid approach. Just make sure to wrap your disposable resources in using blocks. Like this:

using(SqlConnection con = new SqlConnection(Properties.Settings.Default.EventLogPrinterConnectionString))
using (IDbCommand com = con.CreateCommand())
{
    con.Open();
    var sql_com_sel = @"SELECT DISTINCT Users, Pages, Date FROM View_lastactiveUser WHERE (Date >= @ds AND Date <= @dp AND Pages > 0) ORDER BY Date";
    com.CommandText = sql_com_sel;
    com.Parameters.Add("@ds", SqlDbType.DateTime).Value = ds;
    com.Parameters.Add("@dp", SqlDbType.DateTime).Value = dp;
    using (IDataReader dr = com.ExecuteReader())
    {
        while (dr.Read())
        {
            users.Add(new UserDemo() { LastActivity = dr["Date"].ToString(), Pages = int.Parse(dr["Pages"].ToString()), User = dr["Users"].ToString() });
        }
        return users;
    }
}

Of course you could also use an ORM framework such as NHibernate or Entity Framework. Or something lighter such as Dapper .

you could use LinqtoSQL or The ADO.NET Entity Framework Overview

There are also some other solutions like nHibernate, but the first to come nativly with .NET

while such code is acceptable, I highly suggest you to use LINQ to SQL, either the version provided by Microsoft, or the better one found at http://bltoolkit.net , at the moment it has the fastest LINQ parser.

Forgot to mention, that in your if you don't filter the query' parameters from end-user your database will be very vulnerable for SQL injection attacks, especially if you are building a web-site.

No. Not with vanilla ADO.NET. But a more generic approach is something like this:

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string providerName = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;

DbProviderFactory provider = DbProviderFactories.GetFactory(providerName);

using (DbConnection cn = provider.CreateConnection())
{
    cn.ConnectionString = connectionString

    using (DbCommand command = cn.CreateCommand())
    {
        command.CommandText = "GetAllCustomers";
        command.CommandType = CommandType.StoredProcedure;
        cn.Open();

        using (DbDataReader dr = command.ExecuteReader())
        {
            // Do Something...
        }
    }
}

See? No specific ADO.NET driver anywhere. Read more here .

Modern alternatives

The more modern approach is to use a OR/M framework such as entity framework or nhibernate . There are also more lightweight layers such as Dapper or PetaPoco

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM