Pages

Saturday, August 15, 2009

Connect to My SQL from ASP.NET C#

This is a simple code for connecting to MySQL from ASP.NET using C#. Here I have just read a table from the phpBB database. You have to change your connection string accordingly. Here I have read all the data from the table named bb_posts and shown in a grid view. The last function is required.

 public partial class _Default : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("Database=phpbb;Data Source=localhost;User Id=root;Password=");
MySqlDataAdapter adap;
DataSet ds;
Panel panel = new Panel();
GridView gv = new GridView();

protected void Page_Load(object sender, EventArgs e)
{
MySqlCommand command = new MySqlCommand();
adap
= new MySqlDataAdapter("select * from bb_posts", con);
ds
= new DataSet();
adap
.Fill(ds, "bb_posts");

this.Controls.Add(panel);
panel
.Controls.Add(gv);

gv
.DataSource = ds.Tables["bb_posts"];
gv
.DataBind();
gv
.AllowPaging = true;
gv
.AllowSorting = true;
gv
.AutoGenerateDeleteButton = true;


}

public override void VerifyRenderingInServerForm(Control control)
{
return;
}
}

2 comments:

  1. "telnet://192.168.xx.xx" don't show a successful protocol test with java, where as the above supports telnet.

    Need solution
    Ref: Java Networking , O'Relly

    ReplyDelete
  2. Hi, your code is great, but it does not emphasize the polymorphic usabilitiy of the object oriented programming. All of the SQL data providers are developed in a way so that generic SQL data clients can be easily written i.e. You can write Data Access Layer which will retrieve data from different sources and that will be transparent to other layers such as the Business Access Layer.
    I have recently written a post about how to use any SQL data provider, but however, my example is with SQL server (Default) and MySQL. You can read it here and tell me what you think. Connecting MySQL with C#

    ReplyDelete