c#连接必须有效并在获取多个表时打开

时间:2017-04-13 10:10:10

标签: c# mysql

我正在编写一个可以获取4个表的简单程序。我可以单独获取数据,但不能按顺序获取数据。

DBConnection代码:

/*
 * Created by SharpDevelop.
 * Date: 13.04.2017
 * Time: 10:29
 */
using System;
using MySql.Data.MySqlClient;

namespace TWReporting.Database
{
    public class DBConnection
    {
        private DBConnection()
        {
        }

        private string databaseName = "**********";
        private string username = "**********";
        private string password = "**********";

        public string DatabaseName {
            get { return databaseName; }
            set { databaseName = value; }
        }

        public string Password { 
            get { return password; }
            set { password = value; }
        }
        public string Username { 
            get { return username; } 
            set { username = value; }
        }

        private MySqlConnection connection = null;
        public MySqlConnection Connection {
            get { return connection; }
        }

        private static DBConnection _instance = null;
        public static DBConnection Instance()
        {
            if (_instance == null)
                _instance = new DBConnection();
            return _instance;
        }

        public bool IsConnect()
        {
            bool result = true;
            if (Connection == null) {
                if (String.IsNullOrEmpty(databaseName))
                    result = false;
                string connstring = string.Format("Server=localhost; database={0}; UID={1}; password={2}", databaseName, Username, Password);
                connection = new MySqlConnection(connstring);
                connection.Open();
                result = true;
            }
            return result;
        }

        public void Close()
        {
            connection.Close();
        }
    }
}

使用此方法的示例:

public class DataFetcher
{
    public List<TestSessionDut> duts;
    public List<TestSession> testSessions;
    public List<TestScriptRun> testScriptRuns;
    public List<Engine> engines;

    public DataFetcher()
    {
        duts = new List<TestSessionDut>();
        testSessions = new List<TestSession>();
        testScriptRuns = new List<TestScriptRun>();
        engines = new List<Engine>();
        FetchData();
    }

    public void FetchData()
    {
        FetchDuts();
        FetchEngines();
        FetchTestScriptRuns();
        FetchTestSessions();
    }
    public void FetchDuts()
        {
            var dbCon = DBConnection.Instance();
            try 
            {
                if (dbCon.IsConnect())
                {
                    const string query = "SELECT * FROM table";
                    var cmd = new MySqlCommand(query, dbCon.Connection);
                    var reader = cmd.ExecuteReader();
                    while(reader.Read())
                    {
                        var tsd = new TestSessionDut();
                        tsd.ID = reader.GetInt32(0);
                        tsd.Dut = reader.GetString(1);
                        this.duts.Add(tsd);
                    }
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("Fetch duts");
                Console.WriteLine(e.Message);
            }
            finally
            {
                dbCon.Close();
            }
        }

我调用了4个这样的方法,但都来自一个单独的表。我可以分别从所有表中检索数据但是当我一起调用这些方法时它会给出这个消息。

提前致谢。

1 个答案:

答案 0 :(得分:2)

IsConnect方法中,如果连接为空,则初始化连接。但是,下次当您致电IsConnect时,结果将保持false,因为连接不再为空,因此无法进入if(connection == null)

IsConnect方法需要更改如下。

public bool IsConnect()
{
    bool result = false;

    if (connection == null)
    {
        //Checking if all required parameters for connection are having values.
        if (!string.IsNullOrEmpty(databaseName) && !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
        {
            //Creating new connection.
            string connstring = string.Format("Server=.;database={0};UID={1};password={2}", databaseName, Username, Password);
            connection = new SqlConnection(connstring);
        }
    }

    //Check if connection is not null.
    if (connection != null)
    {
        //Check if current status of the connection is open. 
        //If Yes set result = true
        if (connection.State == ConnectionState.Open)
        {
            result = true;
        }
        else
        {
            // If connection not already opened, open it.
            connection.Open();
            result = true;
        }
    }

    return result;
}

Close方法应该在关闭之前检查连接对象及其状态。

public void Close()
{
    if (connection != null && connection.State != ConnectionState.Closed)
    {
        connection.Close();
    }
}