as a developer with a PHP background I've always separated the connection to DB and the Query in 2 separate functions. The logic is why should I call Connect(); every time I want to query to the DB? Isn't that costly?
Now I'm working on a project with C# and SQL Server 2016 and came across the following sample from MSDN.
What I noticed is that they do both the connection and the query in a single method. That looked strange to me as I said I'm a PHP developer, so a few questions:
- Even though the method is asynchronous, wouldn't calling every time I need to query something be costly because it calls
SqlConnection.OpenAsync();
? - Why aren't they closing the connection when they are done?
- Is separating the DB connection and the query a good practice in C#? If so, how would you advise me to do it? And if not, why, and what is an efficient way to connect to and manage a database?
Here is my attempt (untested) to separate connection and query:
private SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
private Task<SqlConnection> connection;
private async Task<SqlConnection> ConnectDB()
{
// Build connection string
builder.DataSource = "localhost";
builder.UserID = "user";
builder.Password = "pass";
builder.InitialCatalog = "test";
// Connect to SQL
SqlConnection connection = new SqlConnection(builder.ConnectionString);
await connection.OpenAsync();
return connection;
}
private async void Query(string cmd)
{
if (cmd == string.Empty || cmd == null)
{
throw new ArgumentException("Query string is empty or null.");
}
SqlCommand command = new SqlCommand(cmd, connection.Result);
await command.ExecuteNonQueryAsync();
}
// Main Form Constructor
public MainForm()
{
connection = ConnectDB();
}
// Example usage?
private void GetAll()
{
Query("SELECT * FROM `test`");
}