Affichage des articles dont le libellé est SGBD. Afficher tous les articles
Affichage des articles dont le libellé est SGBD. Afficher tous les articles

samedi 24 mai 2014

Application mobile : mini SGBD

I- Objet:

 Ce tutoriel consiste à  la réalisation d’un mini SGBD sur des périphériques mobiles, cette application offre les fonctionnalités suivantes:

-          La création d’une BD ;
-          La création d’une table ;
-          L’insertion des enregistrements ;
-          L’affichage.

 II- Présentation de l’application:

       1. L’accueil :


Code source du Form1 « démarrage » :

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace applicationMobile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
         private void button1_Click(object sender, EventArgs e)
        {
            gestion.F2=new ajouBD();
            gestion.F2.Show();
        }
         private void button2_Click(object sender, EventArgs e)
        {
            gestion.tab = new table();
            gestion.tab.Show();
        } 
        private void button4_Click(object sender, EventArgs e)
        {
            gestion.aff = new affich();
            gestion.aff.Show();
        }       
    }
}

  2. Création de la BD :

 Pour la BD on doit remplir les deux champs permettant l’accès à l’application et cliquer après sur le bouton « Valider»(fig3).On aura  le choix (fig4)  entre enregistrer dans le répertoire par défaut ou choisir un autre dossier en utilisant la boite « enregistrer sous »(fig5). Pour vérifier, il suffit d’aller chercher le fichier avec « explorateur des fichier » du mobile(fig6).


Code source relatif à l’ajout de la BD:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;

namespace applicationMobile
{
    public partial class ajouBD : Form
    {
        public ajouBD()
        {
            InitializeComponent();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult res=MessageBox.Show("Enregistrer le fichier dans le repertoire par default:mydoc","enregistrement:",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button1);
            try
            {
                if (res == DialogResult.Yes)
                {                   
                    SqlCeEngine bd = new SqlCeEngine("DataSource=\\My Documents\\" + tB1.Text + ".sdf;Pwd=" + tB2.Text);
                    if (!bd.Verify())
                    {
                        bd.CreateDatabase();
                        this.Close();
                    }
                    else { MessageBox.Show("Le nom existe deja !!!!"); }
                                    }
                else
                {
                    SaveFileDialog diag = new SaveFileDialog();
                    diag.FileName = tB1.Text;
                    diag.Filter = "fichier BD|*.sdf";
                    diag.ShowDialog();
                    SqlCeEngine bd = new SqlCeEngine("DataSource=" + diag.FileName + ";Pwd=" + tB2.Text);
                    bd.CreateDatabase();
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("error: " + ex.Message, "Alert:");
            }
        }
        }
}

 3. Gestion des tables :

En ce qui concerne la gestion des tables, on a le choix entre la création des tables, leur suppression et l’ajout des enregistrements(fig7).

Code source de la Form « gestion des tables »:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace applicationMobile
{
    public partial class table : Form
    {
        public table()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            gestion.F3 = new ajoutab();
            gestion.F3.Show();
            gestion.colonn = "";
        }
            private void button4_Click(object sender, EventArgs e)
        {
            gestion.F4 = new insert();
            gestion.F4.Show();
        }
         private void button2_Click(object sender, EventArgs e)
        {
            gestion.sup = new supp();
            gestion.sup.Show();
        }
         private void button6_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}


Application mobile : mini SGBD (suite)

Création des tables :
        On peut commencer par choisir la BD qu’on veut utiliser soit graphiquement avec un « openfiledialog »(fig9) ou manuellement, si on connait bien sûr le chemin exacte. Il faut ensuite remplir le champ du «password», et le nom de la table (fig8).

Pour ajouter les colonnes composant la table, il faut remplir les champs nécessaires (fig10)(nom,  type, taille…) colonne après colonne en cliquant sur le bouton « ajouter colonne ». Une fois terminé, on doit valider pour créer la table. Pour vérifier il suffit d’aller au programme « query analyzer », ouvrir la BD et chercher la table (fig11).

Code source de la création d’une table:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace applicationMobile
{
    public partial class ajoutab : Form
    {
        int i = 1;
        public ajoutab()
        {
            InitializeComponent();
        }
         private void Form3_Load(object sender, EventArgs e)
        {
            cB1.Items.Add("INT");
            cB1.Items.Add("NVARCHAR");
            cB1.Items.Add("REAL");
            cB1.Items.Add("DATETIME");
            cB1.Items.Add("NCHAR");
          
            lb4.Text = "Nom de la " + i + "° colonne:";
            lb5.Text = "Type de la " + i + "° colonne:";
        }
         private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog diag = new OpenFileDialog();
            diag.Filter = "fichier BD|*.sdf";
            diag.ShowDialog();
            tB1.Text = diag.FileName;
        }
         private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
         private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (gestion.colonn != "" && tB3.Text != "")
                {
                    gestion.conn.ConnectionString = "DataSource=" + tB1.Text + ";Pwd=" + tB2.Text;
                    gestion.conn.Open();
                    gestion.com.CommandText = "CREATE TABLE " + tB3.Text + "(" + gestion.colonn + ")";
                    gestion.com.Connection = gestion.conn;
                    gestion.com.ExecuteNonQuery();
                    gestion.conn.Close();
                }
                else
                {
                    MessageBox.Show("Il faut remplir le nom de la table et au moins ajouter une colonne", "Alert:");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("error:" + ex.Message,"Alert:");
             }
        }
         private void button4_Click(object sender, EventArgs e)
        {
            string pk;
            string notnull;
            string taill;
            if (tB4.Text != "" && cB1.Text != "")
            {
                if (checkBox1.Checked)
                    pk = "PRIMARY KEY";
                else pk = "";
                if (checkBox2.Checked && !checkBox1.Checked)
                    notnull = "NOT NULL";
                else notnull = "";
                if (cB1.Text == "INT" || cB1.Text == "REAL")
                    taill = "";
                else taill = "(" + textBox1.Text + ")";
                if (gestion.colonn == "")
                {
                    gestion.colonn = tB4.Text + " " + cB1.Text+taill+" "+pk+" "+notnull;
                    tB4.Text = "";
                    cB1.Text = null;
                    textBox1.Text = "";
                    checkBox1.Checked = false;
                    checkBox2.Checked = false;
                    i++;
                    lb4.Text = "Nom de la " + i + "° colonne:";
                    lb5.Text = "Type de la " + i + "° colonne:";
                }
                else
                {
                    gestion.colonn = gestion.colonn + " ," + tB4.Text + " " + cB1.Text + taill + " " + pk + " " + notnull;
                    tB4.Text = "";
                    cB1.Text = null;
                    textBox1.Text = "";
                    checkBox1.Checked = false;
                    checkBox2.Checked = false;
                    i++;
                    lb4.Text = "Nom de la " + i + "° colonne:";
                    lb5.Text = "Type de la " + i + "° colonne:";
                }
            }
            else
            {
                MessageBox.Show("Il faut remplir les 2 champs!", "Avertissement:");
            }
        }
    }
}

Suppression d’une table:
Comme à la création d’une table, pour supprimer cette dernière  il suffit de choisir la BD, entrer le password et cliquer sur « valider ». On aura par conséquent la liste des tables(fig12). On choisit la table qu’on veut supprimer et on clique sur « supprimer ». Bien sûr on va avoir un message de confirmation(fig13). 

Si on clique sur « oui » la table sera immédiatement supprimée(fig14).

Code source de la suppression d’une table:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace applicationMobile
{
    public partial class supp : Form
    {
        public supp()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog diag = new OpenFileDialog();
            diag.Filter = "fichier BD|*.sdf";
            diag.ShowDialog();
            tB1.Text = diag.FileName;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                comboBox1.Items.Clear();
                gestion.conn.ConnectionString = "DataSource=" + tB1.Text + ";Pwd=" + tB2.Text;
                gestion.conn.Open();
                gestion.com.CommandText = "SELECT table_name FROM information_schema.tables where table_type='TABLE'; ";
                gestion.com.Connection = gestion.conn;
                gestion.dr = gestion.com.ExecuteReader();
                gestion.dt = new DataTable();
                gestion.dt.Load(gestion.dr);
                gestion.dr = gestion.com.ExecuteReader();
                int i = 0;
                while (gestion.dr.Read())
                {
                    comboBox1.Items.Add(gestion.dt.Rows[i][0].ToString());
                    i++;
                }
                gestion.dr.Close();
                gestion.conn.Close();
                
            }
            catch (Exception ex) { MessageBox.Show("error:" + ex.Message); }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult res = MessageBox.Show("Voulez vous vraiment supprimer la table séléctionnée?","suppresseion",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button1);

                if (res == DialogResult.Yes)
                {
                    gestion.conn.ConnectionString = "DataSource=" + tB1.Text + ";Pwd=" + tB2.Text;
                    gestion.conn.Open();
                    gestion.com.CommandText = "DROP TABLE \"" + comboBox1.Text + "\"";
                    gestion.com.Connection = gestion.conn;
                    gestion.com.ExecuteNonQuery();
                    MessageBox.Show("La table a été bien supprimée");
                    comboBox1.Text = null;
                    gestion.conn.Close();
                }
                           }
            catch (Exception ex) { MessageBox.Show(ex.Message, "Alert"); }
                   }
    }
}
Insertion dans une table :
                  Pour la partie « insertion des enregistrements » on a utilisé presque le même principe de la création d’une table, sauf qu’ici, au lieu d’entrer le nom de la table, l’application se charge de charger un contrôleur de type combobox  par la liste des tables qui se trouvent dans cette BD(fig15). Une fois faite, elle s’adapte selon le nombre des colonnes de la table choisie en donnant le nom de chaque colonne ainsi que son type(fig16).
 Si l’utilisateur ne fait pas d’erreurs, il aura un message de confirmation d’insertion (fig17). Sinon, il aura un message d’erreur.

Code source de l’insertion:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 namespace applicationMobile
{
    public partial class insert : Form
    {
        string colonn="";
        string typ;
        int i=0;
        public insert()
        {
            InitializeComponent();
        }
         private void button1_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog diag = new OpenFileDialog();
            diag.Filter = "fichier BD|*.sdf";
            diag.ShowDialog();
            tB1.Text = diag.FileName;
        }

       private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                gestion.conn.ConnectionString = "DataSource=" + tB1.Text + ";Pwd=" + tB2.Text;
                gestion.conn.Open();
                gestion.com.CommandText = "SELECT table_name FROM information_schema.tables where table_type='TABLE'; ";
                gestion.com.Connection = gestion.conn;
                gestion.dr = gestion.com.ExecuteReader();
                gestion.dt = new DataTable();
                gestion.dt.Load(gestion.dr);
                gestion.dr = gestion.com.ExecuteReader();
                int i = 0;
                while (gestion.dr.Read())
                {
                    comboBox1.Items.Add(gestion.dt.Rows[i][0].ToString());
                    i++;
                }
                gestion.dr.Close();
                gestion.conn.Close();
            }
            catch (Exception ex) { MessageBox.Show("error:" + ex.Message); }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            gestion.conn.ConnectionString = "DataSource=" + tB1.Text + ";Pwd=" + tB2.Text;
            gestion.conn.Open();
            gestion.com.CommandText = "SELECT column_name,data_type FROM information_schema.columns where table_name='" + comboBox1.Text + "'; ";
            gestion.com.Connection = gestion.conn;
            gestion.dr = gestion.com.ExecuteReader();
            gestion.dt = new DataTable();
            gestion.dt.Load(gestion.dr);
            label4.Text = "Valeur de : " + gestion.dt.Rows[0][0] + " de type:" + gestion.dt.Rows[0][1];
            gestion.conn.Close();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            i = 0;
            try
            {
                if (i <= gestion.dt.Rows.Count)
                {
                    typ=gestion.dt.Rows[i][1].ToString();
                    if (colonn == "")
                    {
                        if ( typ == "int" || typ == "real")
                        {
                            colonn = textBox1.Text;
                        }
                        else colonn = "'" + textBox1.Text + "'";
                    }
                    else
                    {
                        if (typ == "int" || typ == "real")
                        {
                            colonn =colonn+","+textBox1.Text;
                        }
                        else colonn =colonn+",'" + textBox1.Text + "'";
                    }
                    i++;
                    textBox1.Text = "";

                    if (i <= gestion.dt.Rows.Count)
                    {
                        label4.Text = "Valeur de : " + gestion.dt.Rows[i][0] + " de type: " + gestion.dt.Rows[i][1];
                    }
                    else { label4.Text = "Valeur de:"; }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "Attention!"); }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
          
            try
            {
                gestion.conn.ConnectionString = "DataSource=" + tB1.Text + ";Pwd=" + tB2.Text;
                gestion.conn.Open();
                gestion.com.CommandText = "insert into "+comboBox1.Text+" values ("+colonn+");";
                gestion.com.Connection = gestion.conn;
                gestion.com.ExecuteNonQuery();
                MessageBox.Show("la ligne a été inseré avec succes:)");
                gestion.conn.Close();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void label4_ParentChanged(object sender, EventArgs e)
        {

        }
    }
}

  4. Affichage :

Pour l’affichage, l’utilisateur est appelé à choisir la BD, entrer le password et cliquer sur valider pour choisir la table qu’il veut afficher(fig18). On aura par conséquent le résultat en cliquant sur le bouton « afficher » (fig19).

Code source de l’affichage:

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace applicationMobile
{
    public partial class affich : Form
    {
        public affich()
        {
            InitializeComponent();
        }
         private void affich_Load(object sender, EventArgs e)
        {
            dataGrid1.Hide();
        }
         private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog diag = new OpenFileDialog();
            diag.Filter = "fichier BD|*.sdf";
            diag.ShowDialog();
            tB1.Text = diag.FileName;
        }
         private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                gestion.conn.ConnectionString = "DataSource=" + tB1.Text + ";Pwd=" + tB2.Text;
                gestion.conn.Open();
                gestion.com.CommandText = "SELECT table_name FROM information_schema.tables where table_type='TABLE'; ";
                gestion.com.Connection = gestion.conn;
                gestion.dr = gestion.com.ExecuteReader();
                gestion.dt = new DataTable();
                gestion.dt.Load(gestion.dr);
                gestion.dr = gestion.com.ExecuteReader();
                comboBox1.Items.Clear();
                int i = 0;
                while (gestion.dr.Read())
                {
                    comboBox1.Items.Add(gestion.dt.Rows[i][0].ToString());
                    i++;
                }
                gestion.dr.Close();
                gestion.conn.Close();
            }
            catch (Exception ex) { MessageBox.Show("error:" + ex.Message); }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                gestion.conn.ConnectionString = "DataSource=" + tB1.Text + ";Pwd=" + tB2.Text;
                gestion.conn.Open();
                gestion.com.CommandText = "SELECT * FROM "+comboBox1.Text+"; ";
                gestion.com.Connection = gestion.conn;
                gestion.dr = gestion.com.ExecuteReader();
                gestion.dt = new DataTable();
                gestion.dt.Load(gestion.dr);
                dataGrid1.DataSource = gestion.dt;
                dataGrid1.Show();
                gestion.dr.Close();
                gestion.conn.Close();
            }
            catch (Exception ex) { MessageBox.Show("error:" + ex.Message); }
        }
    }
}

Code source relatif aux variables globales :

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlServerCe;
using System.Data;

namespace applicationMobile
{
    public static class gestion
    {
        public static SqlCeConnection conn = new SqlCeConnection();
        public static SqlCeCommand com = new SqlCeCommand();
        public static SqlCeDataReader dr;
        public static DataTable dt;
        public static ajouBD F2;
        public static ajoutab F3;
        public static insert F4;
        public static table tab;
        public static supp sup;
        public static affich aff;
        public static String colonn;
    }
}