在C#中打开我的连接到SQL

时间:2014-02-03 00:37:59

标签: c# sql

我在使用C#连接数据库时遇到问题。我可以获取并验证我的连接字符串已被检索,但在尝试打开连接后,它无法打开。没有错误消息,只是在打开时返回false。

using System.Data;
using System.Data.SqlClient;

SqlConnection dConnection = new SqlConnection();
public bool isCurrentOpen;

public string ErrorMsg = "";
public int attempt;
public int MaxRetry = 5;

public bool OpenDBConnection(string ConnectionString)
{
    attempt = 0;          
    if(ConnectionString == null)
        ConnectionString = cConn.SetConnectionString();             

        isCurrentOpen = (dConnection.State == ConnectionState.Open);   

        while (!isCurrentOpen && attempt < MaxRetry)                   
        {
            try
            {
                dConnection.Open();                                 
                attempt++;                                          

                if (isCurrentOpen)                                  
                    break;                                         

            }
            catch (Exception ex)
            {
                ErrorMsg += ex.Message;                            
                attempt++;                                         
            }
        }
        return isCurrentOpen;                                      
    }
}
你怎么看?

这是检索连接字符串的位置

public string ConnectionString = "";

            public string GetConnectionString(string ConnectionString)
    {

        if(ConnectionString == "")
        {
             ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[1].ConnectionString.ToString();
            // Retrieves the Application Settings File and retrieves the Connection String
        }

        return ConnectionString;
    }

     public string SetConnectionString()
     {
         try
        {
            ConnectionString = this.GetConnectionString(ConnectionString);
        }
        catch (Exception ex)
        {
            ErrorMsg += ex.Message;
        }

        return ConnectionString;
    }

更改为不同的数据库并使用SQLCompact数据库并获得相同的结果并再次返回文件中的连接字符串 我没有足够的声誉点来将结果截图给你

3 个答案:

答案 0 :(得分:2)

尝试打开连接后,您不会更新布尔值

isCurrentOpen = (dConnection.State == ConnectionState.Open);   
while (!isCurrentOpen && attempt < MaxRetry)                   
{
    try
    {
        dConnection.Open();                                 
        attempt++;                                          

        // You need to re-evaluate this boolean
        isCurrentOpen = (dConnection.State == ConnectionState.Open);   

        // And, there is no need to break out here, because the loop will terminate 
        // itself if the isCurrentOpen == true
        // if (isCurrentOpen)                                  
        //      break;                                         
    }
    ....
}
return isCurrentOpen;     

编辑查看您的编辑,似乎您没有将ConnectionString传递给连接对象。没有它,连接就不知道如何打开数据库

public bool OpenDBConnection(string ConnectionString)
{
    attempt = 0;          
    isCurrentOpen = (dConnection.State == ConnectionState.Open);   
    if(isCurrentOpen == false)
    {
       // If no connectionstring received, get it from the config
       if(ConnectionString == null)
           ConnectionString = cConn.GetConnectionString();    

       // Assign the connectionstring to the connection to be opened
       dConnection.ConnectionString = ConnectionString;
       while (!isCurrentOpen && attempt < MaxRetry)                   
       {
           try
           {
               dConnection.Open();   
               ......

答案 1 :(得分:0)

在将连接字符串分配给数据库连接对象时,在代码中找不到。您可以尝试使用开放式连接方法进行分配吗?

要回答第二个问题,请如何在当前库中解决此问题。这就是我建议你做的事情:

public bool OpenDBConnection(string ConnectionString)
{
    attempt = 0;          
    if(ConnectionString == null)
        ConnectionString = cConn.SetConnectionString();             
    isCurrentOpen = (dConnection.State == ConnectionState.Open);   

    if (!isCurrentOpen) //to keep up with your logic in case a connection is already opened.
         dConnection = new SqlConnection(ConnectionString); //Initialize Database connection with the Connection String    
     ...

答案 2 :(得分:0)

你可以这样做......

将连接字符串存储在App.Config文件中,并为您的项目制作全局类

以下是App.Config文件的示例代码

<?xml version="1.0" encoding="utf-8" ?>

 <configuration>
 <appSettings>
<add key="ConnString" value="Data Source=.;Initial Catalog=yourdatabase;Integrated Security=True" />
</appSettings>
</configuration>

全球类代码

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;

namespace DAL

{

 public class GlobalClass

{
    public string connectionString;

    public GlobalClass() 
    {
        connectionString = System.Configuration.ConfigurationManager.AppSettings.Get("ConnString");
    }
}}

并且您可以将Global类继承到您的剩余项目类我希望这可以帮助您

这里我们考虑员工类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

 namespace Employe
 {
   public class Employe : GlobalClass
{
    public Employe()
    {
    }
 //Sample Method 
     public DataTable FillRoleComboBox()
    {
        DataTable dt = new DataTable();
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand comm = new SqlCommand("select * from TBLEMPLOYEE", conn);
        SqlDataAdapter SDA = new SqlDataAdapter(comm);
        SDA.SelectCommand = comm;
        SDA.Fill(dt);
        return dt;
    }
}
}