在c#应用程序中集中保持连接字符串和连接对象

时间:2014-02-28 11:13:23

标签: c# database string class connection

我是C#(当然是.net)的初学者,也是我最后一年开发工资单系统的项目。现在我有一些关于ado.net sql连接对象的问题。 为了集中保持连接字符串,我使用了单独的类调用db。再向这个集中思维迈出了一步,我已经在db class中集中初始化了连接对象,如下所示。

class db
{

string connectionString = ("connection string will be here...");

    public SqlConnection GetConn()
    {
        SqlConnection NewConn = new SqlConnection(connectionString);
        return NewConn;
    }
} 

现在我在我的应用程序中使用此连接对象如下... 我只想知道将来是否会因为这种做法而面临问题,并且如果专家之一能够解释我在这方面的最佳做法,我也很感激。

提前致谢

class client
 {

    db NewDB = new db(); // db class is instantiated...
    SqlConnection newCon; // object referece newConn is created...


    //Method to insert new clients to 'client' table

    public void addNewClient(DateTime entDate, client NewClient)
    {
        try
        {
            newCon = NewDB.GetConn(); // connection object is assigned to newCon... but this is optional and I put this for the clarity

            string CommandString = "INSERT INTO client(Client_Name, C_Add, Contact_Person, C_Mob_No, C_Tel_No, Remarks, Ent_Date)" +
                                    " VALUES (@CName, @CAdd, @CPerson, @CMob, @CTel, @Remarks, @entDate)";


            SqlCommand SqlCom = new SqlCommand();
            SqlCom.CommandText = CommandString;
            SqlCom.Parameters.Add("@CName", SqlDbType.VarChar).Value = NewClient.CName;
            SqlCom.Parameters.Add("@CAdd", SqlDbType.VarChar).Value = NewClient.CAdd;
            SqlCom.Parameters.Add("@CPerson", SqlDbType.VarChar).Value = NewClient.CPerson;
            SqlCom.Parameters.Add("@CMob", SqlDbType.Char).Value = NewClient.CMob;
            SqlCom.Parameters.Add("@CTel", SqlDbType.Char).Value = NewClient.CTel;
            SqlCom.Parameters.Add("@Remarks", SqlDbType.VarChar).Value = NewClient.Remarks;
            SqlCom.Parameters.Add("@entDate", SqlDbType.Date).Value = entDate;
            SqlCom.Connection = newCon;
            newCon.Open();

            SqlCom.ExecuteNonQuery();
        }
        catch
        {
            throw;
        }

        finally
        {
            newCon.Close(); // newCon object is global to entire class so can call its close method.
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您不需要使用全局连接对象。您的数据库连接存储在连接池中。所以你不会失去联系。 Read more about connections pooling

答案 1 :(得分:0)

查看您的客户端类,在代码中编写原始SQl是不好的做法。编写存储过程并从传递参数的代码中调用它是更好的做法。

public void addNewClient(DateTime entDate, client NewClient)
    {
        try
        {
            newCon = NewDB.GetConn(); // create connection 
            conn.Open(); //open connection 

            // create a command object identifying the stored procedure
            SqlCommand SqlCom = new SqlCommand("Store Procedure name", newConn);

           // add parameter to sql command, which is passed to the stored procedure
           SqlCom .Parameters.Add(new SqlParameter("@CName", NewClient.CName));

          // Rest of parameters

          // execute the command
          cmd.ExecuteReader();
      }
  }

创建一个存储连接的类是很好的做法。但是你可以进一步扩展它。

public struct slqParameters
{

    public object ParamData { get; set; }
    public string ParamKey { get; set; }
    public SqlDbType ParamDatabaseType { get; set; }
    public int ParamSize { get; set; }
}

class db
{
    private string connectionString = ("connection string will be here...");

    public static void ExecuteStoreProcedure(string ProcedureName, ref slqParameters[]  CommandParameters)
     {
         string str_ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
         try
         {
             using (SqlConnection sqlConnection = new SqlConnection(str_ConnectionString))
             {
                 using (SqlCommand sqlCommand = new SqlCommand(sProcedureName, sqlConnection) { CommandType = CommandType.StoredProcedure })
                 {
                     // Add all the parameters to the sql command.
                     foreach (slqParametersParameter in CommandParameters)
                     {
                         // Add a parameter
                         sqlCommand.Parameters.Add(new SqlParameter(Parameter.ParamKey, Parameter._ParamDatabaseType , Parameter._ParamSize ) { Value = Parameter.ParamData  });
                        }
                        sqlConnection.Open();
                        DataTable dtTable = new DataTable();
                        sqlCommand.ExecuteReader())
                    }
                }
            }
            catch (Exception error)
            {
                throw error;
            }
        }
}

这只是一个粗略的指南,因为我还没有测试过,但它应该可行

在页面上使用

Public SomeMethod()
{
     slqParameters[] parameters = new Parameters[1]
    {
        new sqlParameters{ ParamData  = , paramKey = "@CName", ParamDatabaseType  = NewClient.CName}
    };

    db.ExecuteStoreProcedure("Store Procedure name", parameters);
}