dusk
dusk

Reputation: 1313

How can I get a MySqlConnection object from a DLL

My goal is to create a DLL that can be used with several different programs that will return the MySqlConnection object. That way if the credentials ever change, it will only need to be modified in one place.

Right now I can get my MySqlConnection object successfully from another C# file included in the project, but when I try to retrieve it from my DLL instead I get the following error:

Unhandled Exception: System.InvalidOperationException: Connection must be valid and open.

Can anyone spot the error in my code or my logic? Is there a better way to accomplish this? Thanks in advance!

My DLL code

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

//For MySql connections
using MySql.Data.MySqlClient;

namespace LinMySqlConnections
{
    public class MySqlMain
    {
       public static MySqlConnection OpenConnection()
       {
         string server = "database.address";
         string database = "databaseName";
         string user = "dbUser";
         string pass = "dbPass";

         string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + 
                                    user + ";" + "PASSWORD=" + pass + ";";

         MySqlConnection connection = new MySqlConnection(connectionString);

         return connection;
    }
}

My Main code

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

using MySql.Data.MySqlClient;
using LinMySqlConnections;

namespace ODSTesting
{
  class Program
  {
    static void Main(string[] args)
    {
      MySqlConnection mainDB = LinMySqlConnections.MySqlMain.OpenConnection();

      if (mainDB != null)
      {
        string query1 = "SELECT * FROM table";

          MySqlCommand cmd = new MySqlCommand(query1, mainDB);
          MySqlDataReader dataReader = cmd.ExecuteReader();
        }
        else
          Console.WriteLine("mainDB was null dude");
    }
  }
}

Upvotes: 0

Views: 814

Answers (1)

Andrey Belykh
Andrey Belykh

Reputation: 2654

The connection is not open

connection.Open();

Upvotes: 1

Related Questions