This thread is a continuation of http://stackoverflow.com/questions/2220422/is-there-a-reason-to-check-for-null-inside-multiple-using-clausule-in-c
I've noticed that resharper lets me define using without opening any opening/closing bracket like in the method below (but then i can't use defined vars later on if the brackets ain't there, other then the one that is used exactly beneath defined using):
public static string sqlGetDatabaseRows() {
string varRows = "";
const string preparedCommand = @"
SELECT SUM(row_count) AS 'Rows'
FROM sys.dm_db_partition_stats
WHERE index_id IN (0,1)
AND OBJECTPROPERTY([object_id], 'IsMsShipped') = 0;";
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP))
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
while (sqlQueryResult.Read()) {
varRows = sqlQueryResult["Rows"].ToString();
}
sqlQueryResult.Close();
}
return varRows;
}
Is it good? Or should i use it like this?
public static string sqlGetDatabaseRows() {
string varRows = "";
const string preparedCommand = @"
SELECT SUM(row_count) AS 'Rows'
FROM sys.dm_db_partition_stats
WHERE index_id IN (0,1)
AND OBJECTPROPERTY([object_id], 'IsMsShipped') = 0;";
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP)) {
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null) {
while (sqlQueryResult.Read()) {
varRows = sqlQueryResult["Rows"].ToString();
}
sqlQueryResult.Close();
}
varConnection.Close();
}
return varRows;
}
sqlConnectOneTime looks like this:
public static SqlConnection sqlConnectOneTime(string varSqlConnectionDetails) {
SqlConnection sqlConnection = new SqlConnection(varSqlConnectionDetails);
sqlConnect(sqlConnection);
if (sqlConnection.State == ConnectionState.Open) {
return sqlConnection;
}
return null;
}
My questions are:
Should I be closing varConnection by using varConnection.Close() and sqlQueryResult.Close(); in the end? (but this enforces use of brackets) or will the connection close itself when using is done.
Should i be checking for NULL for varConnection since it's possible it will return null (on the other hand resharper doesn't complain here).
Is there some better approach i could use for defining sqlConnectOneTime ? Like when the connection fails to open it should return ConnectionState.Closed instead of null?
Also just on a note i open up new connection every time i execute new query / update / insert since i am using threading and it was the smartest idea i could come up at that very moment. Feel free to suggest better one :-)
I am asking about all this since i want to better understand whole process and stop making silly mistakes so be gentle with me.
MadBoy
Edit: modified question if varConnection.Close() and sqlQueryResult.Close() are nessecary if using is used.