Is this code correct in means of Try/Catch? I need to value whether the action is done or not to inform the user about the result, so I will then get the bool value to know if connection was successful.
public static bool CreateSQLDatabaseTable() { var connString = "Server=localhost\SQLEXPRESS;Integrated Security = SSPI; database = MyDB"; string cmdText = "SELECT count(*) as Exist from INFORMATION_SCHEMA.TABLES where table_name =@Product"; try { using (var sqlConnection = new SqlConnection(connString)) { using (var sqlCmd = new SqlCommand(cmdText, sqlConnection)) { sqlCmd.Parameters.Add("@Product", System.Data.SqlDbType.NVarChar).Value = "Product"; sqlConnection.Open(); sqlCmd.ExecuteScalar(); if ((int)sqlCmd.ExecuteScalar() != 1) { using (SqlCommand command = new SqlCommand("CREATE TABLE Product (Id INT, UserId TEXT, CreationDate TEXT, Name TEXT)", sqlConnection)) { command.ExecuteNonQuery(); return true; } } } } return false; } catch { return false; } }
Advertisement
Answer
Your method can actually have 3 outcomes:
- The table was created successfully (method returns true)
- The table already exists (method returns false)
- There was an error trying to create the table (exception is thrown)
So you should handle the exception outside of this method and you should not blindly catch all Exceptions. You should only handle the SqlException
so that other exceptions will not be handled. Also you should be logging the exception somewhere as a good practice.
For more information on the SqlException
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception(v=vs.110).aspx
public static bool CreateSQLDatabaseTable() { var connString = "Server=localhost\SQLEXPRESS;Integrated Security = SSPI; database = MyDB"; string cmdText = "SELECT count(*) as Exist from INFORMATION_SCHEMA.TABLES where table_name =@Product"; using (var sqlConnection = new SqlConnection(connString)) { using (var sqlCmd = new SqlCommand(cmdText, sqlConnection)) { sqlCmd.Parameters.Add("@Product", System.Data.SqlDbType.NVarChar).Value = "Product"; sqlConnection.Open(); sqlCmd.ExecuteScalar(); if ((int)sqlCmd.ExecuteScalar() != 1) { using (SqlCommand command = new SqlCommand("CREATE TABLE Product (Id INT, UserId TEXT, CreationDate TEXT, Name TEXT)", sqlConnection)) { command.ExecuteNonQuery(); return true; } } } } return false; } public static void Main() { try { bool wasCreated = CreateSQLDatabaseTable(); } catch (SqlException ex) { // Handle the SQL Exception as you wish Console.WriteLine(ex.ToString()); } }