简体   繁体   中英

Method including SQLConnection - good approach?

Hey, I currently have this method in my code:

public static DataSet PrepareDataSet(some params)
{
    SqlConnection sqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
    SqlDataAdapter adapter = new SqlDataAdapter(Utils.EscapeProcedureName(...), sqlConnection);
    adapter.SelectCommand.CommandType = CommandType.StoredProcedure;

    //do some stuff with the adapter using the params

    sqlConnection.Open();
    DataSet dataSet= new DataSet();
    adapter.Fill(dataSet);
    sqlConnection.Close();
    return dataSet;
}

This code is called from an aspx.cs page. Is it a good approach to have the SQL connection stuff and the adapter inside the method? If not, how can that be refactored? Somehow I think this is not good for testing for example ...

Thanks for ur ideas :)

No it is not good approach to make a data access in from the page code.

Try to make your application in layered approach N-Tier , or use MVC Design pattern.

Try to separate the Data Access logic and Business logic in your application so it will be easier for code maintainability and readability; you can even use auto generating tools to increase the code speed and quality by eliminating redundant work. Read more about ORM ; it will help you a lot about good coding practices.

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