连接SQL Server 2008 R2无法正常工作

本文关键字:常工作 工作 Server SQL 2008 R2 连接 | 更新日期: 2023-09-27 17:54:59

我试着测试我的应用程序是否连接到本地数据库。我没有得到任何错误,所以我不太明白为什么它不工作。我只得到"无连接"输出。我试图调试它,但得到连接= null。我有SQL Server 2008 R2(混合身份验证)和Visual Studio 2008 sp1。我尝试使用Windows和SQL Server身份验证连接,但都不起作用。

这是我的web.config文件。

<connectionStrings>
    <add name="MyDbConn" 
         connectionString="Data Source=local;Initial Catalog=Sample;Integrated Security=True;" 
         providerName="System.Data.SqlClient" />
</connectionStrings>

Default.aspx.cs

public partial class _Default: System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e) 
    {
    }
    protected void btnTestDb_Click(object sender, EventArgs e)
    {
        try {
            SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=Sample; Integrated Security=SSPI");
            connection.Open();
            if (connection != null && connection.State == ConnectionState.Closed) {
                Response.Write("Connection OK!");
                connection.Close();
            } else {
                Response.Write("No Connection!");
            }
        } catch {
            Response.Write("No Connection!");
        }
    }
}

连接SQL Server 2008 R2无法正常工作

 //Try this
 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn"].ToString());
protected void btnTestDb_Click(object sender, EventArgs e)
 {
    try {
       con.Open();
        if (con.State == ConnectionState.Open)
        {
            Response.Write("Connection Open");
        }
        else
        {
            Response.Write("Connection Closed");
        }
        con.Close();
    } catch {
        Response.Write("No Connection!");
    }
}

试图打开连接的代码中有一些问题。

当您尝试调用连接时。打开,结果是一个异常,如果你有问题或只是一个连接与它的ConnectionState=Open。
如果ConnectionState关闭,您的代码反而给出"Connection OK"消息,但是,当然,刚刚调用了Open,如果您没有问题,那么ConnectionState是打开的。

你可以试试下面的代码....

protected void btnTestDb_Click(object sender, EventArgs e)
{
    string result = TestConnection();
    Response.Write(result);
}
private string TestConnection()
{
    try
    {
        using(SqlConnection connection = new SqlConnection("...."))
        {
             connection.Open();
             return "Connection opened correctly";
        }
    }
    catch(Exception ex)
    {
        return "Error opening the connection:" + ex.Message;
    }
}

编写的ado.net代码肯定会打开连接,但我怀疑连接字符串是否会这样做。从此专用站点选择合适的connectionstring