2

我对 c# 还是很陌生,我在一个页面上有多个计数查询。我不需要在其他任何地方使用这些查询,因此避免了创建类。尽管如此,我可以帮助但认为必须有一种更有效的方法,但我想知道那会是什么!

这是一个例子

    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);
        }
    }
}
4

4 回答 4

3

以下存储库适用于 SQL Server。

基本上,您可以发出常规或参数化查询。如果要使用具有强类型数字和日期的模型,您可以将参数作为所有字符串传递,或者仅作为对象传递。

如果您在开发中不使用这样的构造,您可以取出发布模式信息,这只是为了更容易在开发和生产数据库之间切换而无需编码更改。

一个示例用法是:

      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);

这里是课堂...

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;
            }

        }
于 2013-04-09T15:15:36.290 回答
1

如果你只做 1 个地方的东西,通常你会让一切变得不那么可读。所以我可能会避免它。然而,这是一种常见的模式,你会帮自己一个忙,为此编写一个带有一些函数的实用程序类。

//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);
}

然后像这样使用

UserUpcoming.Text = Query("SELECT COUNT(*) FROM vw_dash_user_upcoming WHERE Employee_ID = @0", crd["employee_id"].ToString())[0][0];
于 2013-04-09T14:55:18.947 回答
0

我喜欢为数据库中的每个表设置一个单独的类。在您的情况下,我将有一个名为 vw_dash_user_upcoming 的单独类,这将有一个类似于...的静态方法

public static int CountEmployees(int employeeId) {
    int returnValue;
    // do database stuff here
    return returnValue;
}

我通常在我的项目中创建一个名为“数据库”的文件夹和命名空间,所有数据库的东西都放在那里。那里没有任何不是数据库访问的内容。对我来说,这确实有助于让事情井井有条,尤其是在大型项目中。

于 2013-04-09T14:53:03.200 回答
0

我个人会创建一个单独的类,仅仅是因为将具有完全不同职责的代码片段保留在一个类中并不是一个好主意。当分成小类时,代码更容易阅读和维护。

无论如何,与数据库的通信都应该分开,以便更容易在数据源(例如不同的数据库服务器)之间切换。

于 2013-04-09T14:55:50.190 回答