简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM