sqlchild
sqlchild

Reputation: 9064

Creating a single connection file for my C# .NET Winform Application

I want to make a single connection file , using which , all the Forms of my winform application should connect to the online mysql database and select,update & insert data.

I have named the connection file as CONNECTION.CS, connection string is :

OdbcConnection conn = new OdbcConnection("Driver={MySQL ODBC 5.1 Driver};uid=ab ; password=pass;server=www.myweb.com;database=mydb;port=3306"); 

Now , how do I use it in the Form1.cs,Form2.cs ..........to establish connection to the database and start inserting and retreiving data? Please help.

Do i need to inherit this Connection.cs in all the Forms? Please help with code

Upvotes: 0

Views: 2457

Answers (1)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79889

I think it will be easer if you define it in the app.config file

<appSettings>
  <add key="ConnectionString" value="Driver={MySQL ODBC 5.1 Driver};uid=ab ; password=pass;server=www.myweb.com;database=mydb;port=3306" />
   </appSettings>
</configuration>

so whenever you want to get a connectionstring you can get it :

string strConn = ConfigurationManager.AppSettings["ConnectionString"];

or you can use a class as a data access layer :

class Connection
{
     OleDbConnection conn;
     OleDbCommand cmd;
     public Connection()
     {
          string connnstr = "Driver={MySQL ODBC 5.1 Driver};uid=ab ; password=pass;server=www.myweb.com;database=mydb;port=3306";
          conn = new OleDbConnection(connstr);
          cmd = new OleDbCommand();
          cmd.Connection = conn;
     }
     public OleDbDataReader GetData()
     {
        ....
     }
}

then whenever you want to getdata just

Connection conn = new Connection();
OleDbDataReader dr = conn.getData();

by this way you just define a single connection file.

Upvotes: 2

Related Questions