.NET MySql and DataSet

Tools And links

Example 1 : populating from a database

// it's a small sqlwrapper : it does nothing except starting and ending correctly connection
SqlWrapper sql = new SqlWrapper( Sql_domaine, Sql_login, Sql_password, Sql_table );
 
// Create a dataset object and fill with data using data adapter's Fill method 
DataSet ds = new DataSet(); 
 
string query = "SELECT * FROM COMMANDES";
 
sql.PreQuery(); // create a connection
MySqlDataAdapter da = new MySqlDataAdapter( query, sql.sqlcon ); // sqlcon : the connection
da.Fill(ds, "Commandes"); 
sql.PostQuery();
 
query = "SELECT * FROM COMMANDES_ARTICLES"; 
sql.PreQuery();
da = new MySqlDataAdapter( query, sql.sqlcon );
da.Fill(ds, "Articles");
sql.PostQuery();
 
// add a relation between the ID of the command and the child table COMMANDE_ID
ds.Relations.Add( "CommandesToArticles", 
	ds.Tables["Commandes"].Columns["ID"],
	ds.Tables["Articles"].Columns["COMMANDE_ID"] );
 
// And it's done. You have the dataset, with one relation populated with data from MySQL

Example 2 : populating manually

ds = new DataSet("Commandes");
			
// Create Commandes Table
DataTable dtCommandes = new DataTable("Commandes");
dtCommandes.Columns.Add("ID", typeof(int));
dtCommandes.Columns.Add("Client", typeof(string));
dtCommandes.Columns.Add("Infos", typeof(string));
// Make ‘ID’ a primary key in Elements table
dtCommandes.PrimaryKey = new DataColumn[]{dtCommandes.Columns["ID"]};
			
// Create Articles Table
DataTable dtArticles = new DataTable("Articles");
dtArticles.Columns.Add("ID", typeof(int));
dtArticles.Columns.Add("Descrition", typeof(string));
dtArticles.Columns.Add("Quantite", typeof(int));
			
// Add tables to the Dataset
ds.Tables.Add(dtCommandes);
ds.Tables.Add(dtArticles);
ds.Relations.Add( "CommandesToArticles", 
    ds.Tables["Commandes"].Columns["ID"],
    ds.Tables["Articles"].Columns["ID"] );
 
dtCommandes = ds.Tables["Commandes"];
dtArticles = ds.Tables["Articles"];
DataRow drCommande;
DataRow drArticle;
 
// filling
for(int cmd=0; cmd<10; cmd++)
{
    drCommande = dtCommandes.NewRow();
    drCommande["ID"] = cmd;
    drCommande["Client"] = string.Format("clientpipo numero {0}", cmd);
    drCommande["Infos"] = drCommande["Client"].GetHashCode().ToString();
    dtCommandes.Rows.Add( drCommande );
    
    for(int art=0; art<5; art++)
    {
        drArticle = dtArticles.NewRow();
	drArticle["ID"] = cmd;
	drArticle["Description"] = "pipo";
        drArticle["Quantite"] = art;
	dtArticles.Rows.Add(drArticle);
    }
}
 
  net_-_mysql_and_dataset.txt · Dernier changement: 2006/09/14 21:16