在C#中正确使用Try Catch进行SQL连接

时间:2018-05-18 21:58:56

标签: c# sql sql-server exception-handling try-catch

这个代码在Try / Catch方面是否正确?我需要重视操作是否已完成以通知用户结果,因此我将获取bool值以了解连接是否成功。

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

2 个答案:

答案 0 :(得分:2)

您的方法实际上可以有3个结果:

  1. 表已成功创建(方法返回true)
  2. 该表已存在(方法返回false)
  3. 尝试创建表时出错(抛出异常)
  4. 因此,您应该在此方法之外处理异常,并且不应盲目捕获所有异常。您应该只处理SqlException,以便不处理其他异常。此外,您应该将异常记录在某处作为一种良好做法。

    有关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());
        }
    }
    

答案 1 :(得分:0)

我将通过一个查询来解决这种问题,该查询会自行检查是否存在并返回是否已创建。

    public static bool CreateSQLDatabaseTable() {
        var connString = "...";
        const string tableName = "Product";
        string cmdText = $"IF EXISTS (SELECT TOP(1) 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG = DB_NAME() AND TABLE_SCHEMA = 'dbo' AND TABLE_NAME = '{tableName}' AND TABLE_TYPE = 'BASE TABLE') BEGIN\r\n" +
                         $"  SELECT CAST(0 AS BIT) AS CreatedNow\r\n" +
                         $"END ELSE BEGIN\r\n" +
                         $"  CREATE TABLE dbo.{tableName}(Id INT, CreatorId INT, CreationDate DATETIME, CreationDateUtc DATETIME, Name NVARCHAR)\r\n" +
                         $"  SELECT CAST(1 AS BIT) AS CreatedNow\r\n" +
                         $"END";

        using (var sqlConnection = new SqlConnection(connString)) {
            using (var sqlCmd = new SqlCommand(cmdText, sqlConnection)) {
                sqlConnection.Open();
                return (bool)sqlCmd.ExecuteScalar();
            }
        }
    }