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

在c#应用程序中集中保持连接字符串和连接对象,c#,database,string,class,connection,C#,Database,String,Class,Connection,我是C#(当然是.net)的初学者,在我的最后一年项目中,我正在开发一个工资系统。现在我有一些关于ado.net sql连接对象的问题。 为了集中保存连接字符串,我使用了一个单独的类调用db。在这个集中化思想的另一个步骤中,我已经在这个db类中集中地初始化了connection对象,如下所示 class db { string connectionString = ("connection string will be here..."); public SqlConnection

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

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

您不需要使用全局连接对象。数据库连接存储在连接池中。这样你就不会失去联系

看看您的客户机类,在代码中编写原始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);
}

谢谢你的建议。因此,我将在db类中集中构建连接字符串,并在方法级别创建连接对象。感谢您的解释和代码示例。我认为这是分离数据和逻辑的三轮胎开发模型。以这种方式开发OO系统是一种好的实践吗?