About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).

Sunday, February 05, 2006

How To: Use mySql with ASP.net/C#

Need to use:
using System.Data;
using System.Data.Odbc;

Define Global Variables:
private System.Data.Odbc.OdbcConnection OdbcCon;
private System.Data.Odbc.OdbcCommand OdbcCom;
private System.Data.Odbc.OdbcDataReader OdbcDR;

DataReader is a read only access, making communication to the database(s) a lot quicker.

Connection String all on one line:
ConStr = "DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;PORT=3306;
DATABASE=databasename;UID=username;PWD=password;OPTION=3";

Your Query:
string ComStr = "select * from agent where state ='" + TextBox1.Text + "'";

Make Connection:
OdbcCon = new System.Data.Odbc.OdbcConnection(ConStr);
Make Query:
OdbcCom = new OdbcCommand(ComStr,OdbcCon);

Now do your try block:

try
{
   if(OdbcCon.State == ConnectionState.Closed)
   {
      OdbcCon.Open();
   }

   OdbcDR = OdbcCom.ExecuteReader();
   while(OdbcDR.Read())
   {
      result.Text = "The results of the query are:";
      Label1.Text = "State: "+OdbcDR[0].ToString();
      Label2.Text = "Value: "+OdbcDR[1].ToString();
      Label3.Text = "Visted: "+OdbcDR[2].ToString()+ " times";
   }
   }OdbcCon.Close();
}
catch(Exception Ex)
{
   // An error occured, give details
   string warning = Ex.ToString();
   Page.Response.Write(warning);
}

No comments: