尝试连接SQL Server

时间:2017-07-21 14:17:48

标签: c# asp.net sql-server azure asp.net-web-api2

我在Windows Azure中使用SQL Server 2016创建了一个虚拟机。此虚拟机具有Azure防火墙,我允许IP连接到服务器。我的项目也是一个带有ADO.NET for Data Access Layer的ASP.NET Web API 2。

事情已经完成了;一切都很好(好!)。但是,如果我尝试使用未添加到防火墙规则的IP从另一个地方连接,我不会收到任何错误,只是仍然尝试执行命令。通常,如果我使用SQL Managment,我会收到错误。

这是我的连接字符串中的参数

Server=vm.XXXXXX.azure.com;Database={database};User ID={userid};Password={password};Encrypt=True;TrustServerCertificate=True;Connection Timeout=300;ConnectRetryCount=4;ConnectRetryInterval=1

所以,这是我执行的提取代码:

using (SqlConnection dbConnection = new SqlConnection(myCString))
{
    using (SqlCommand dbCommand = new SqlCommand())
    {
        string queryString;
        queryString = "SELECT * FROM table WHERE (ID = @ID) ";
        dbCommand.Parameters.Add(Utilities.GetSQLParameter("ID", 1234, SqlDbType.VarChar));

        dbCommand.CommandText = queryString;
        dbCommand.Connection = dbConnection;

        dbConnection.Open();
        using (SqlDataReader dr = dbCommand.ExecuteReader())
        {
            if (dr.Read())
            {
                Value = dr[Field].ToString();
            }
            else
            {
                Value = "";
            }
        }
    }
}

总之,如果我找不到VM,我想得到错误,因为防火墙阻止了访问。

2 个答案:

答案 0 :(得分:0)

连接失败发生在dbConnection.Open。 将代码包装在try/catch块中,如果发生错误

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx

可以找到可用的可捕捉例外列表
try
{
    dbConnection.Open();
    using (SqlDataReader dr = dbCommand.ExecuteReader())
    {
        if (dr.Read())
        {
            Value = dr[Field].ToString();
        }
        else
        {
            Value = "";
        }
    }
}
catch(Exception ex)
{
    //Do some treatment
}
finally
{
    //If connection has been opened, close it.
    if(dbConnection.ConnectionState == ConnectionState.Open)
    {
        dbConnection.Close();  
    } 

}

答案 1 :(得分:0)

我建议您使用USING清除所有“托管资源”
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnStringName"].ToString()))
using (SqlCommand mySqlCommand = new SqlCommand())
{
    try
    {
        conn.Open();
        mySqlCommand.Connection = conn;
        mySqlCommand.CommandType = CommandType.StoredProcedure;
        mySqlCommand.CommandText = "getCities";
        mySqlCommand.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ConnectionTimeout"].ToString());

        mySqlCommand.Parameters.Add("@param", SqlDbType.VarChar).Value = param;     
        da.SelectCommand = mySqlCommand;
        da.Fill(ds, "cities");
    }
    catch (Exception ex)
    {            
      // LOG HERE the errors    
    }
} // end using