Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. class to open its database

class to open its database

Scheduled Pinned Locked Moved C#
databasesecurity
10 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    ago2486
    wrote on last edited by
    #1

    public class ConnectionDB
    {

        // Declaration des objets sql
        public OleDbConnection sql\_con;
     
        // declaration de la methode connecter
        public void CONNECTER()
        {
            try
            {
                string connetionString = null;
                //connection à la base de donnée avec mot de passe
                connetionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Application.StartupPath + @"\\DB\_CaisseEnregistreuse.mdb;Persist Security Info=True;Jet OLEDB:Database Password=B@sta08091987";
                sql\_con = new OleDbConnection(connetionString);
                sql\_con.Open();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erreur de connexion à la base donnée" + ex.ToString());
            }
    
            
        }
    
        // declaration de la methode deconnecter
        public void DECONNECTER()
        {
            try
            {
    
                if (sql\_con.State == ConnectionState.Open)
                {
    
                    sql\_con.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erreur de deconnexion à la base donnée" + ex.ToString());
            }
        }
    

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
    
        }
    

    ConnectionDB d = new ConnectionDB();

    using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                {
                    cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                    d.sql\_con.Open();
                    d.DR = cmbox.ExecuteReader();
    
                    try
                    {
                        while (d.DR.Read())
                        {
                            CmbRef\_Produit.Items.Add(d.DR\["Code\_article"\]).ToString();
                        }
    
                        //si le textbox est vide
                        if (string.IsNullOrWhiteSpace(CmbRef\_Produit.Text ))
                        {
                            // Message box
    
                            Lbl\_affich\_TxtQteStock.Text = "";
                            Lbl\_Affich\_Designation.Text = "";
                            Lbl\_Affich\_PrixUnitaire.Text = "";
                        }
    
                    }
                    catch (Exception ex)
    
    L OriginalGriffO 2 Replies Last reply
    0
    • A ago2486

      public class ConnectionDB
      {

          // Declaration des objets sql
          public OleDbConnection sql\_con;
       
          // declaration de la methode connecter
          public void CONNECTER()
          {
              try
              {
                  string connetionString = null;
                  //connection à la base de donnée avec mot de passe
                  connetionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Application.StartupPath + @"\\DB\_CaisseEnregistreuse.mdb;Persist Security Info=True;Jet OLEDB:Database Password=B@sta08091987";
                  sql\_con = new OleDbConnection(connetionString);
                  sql\_con.Open();
                  
              }
              catch (Exception ex)
              {
                  MessageBox.Show("Erreur de connexion à la base donnée" + ex.ToString());
              }
      
              
          }
      
          // declaration de la methode deconnecter
          public void DECONNECTER()
          {
              try
              {
      
                  if (sql\_con.State == ConnectionState.Open)
                  {
      
                      sql\_con.Close();
                  }
              }
              catch (Exception ex)
              {
                  MessageBox.Show("Erreur de deconnexion à la base donnée" + ex.ToString());
              }
          }
      

      public partial class Form1 : Form
      {

          public Form1()
          {
              InitializeComponent();
      
          }
      

      ConnectionDB d = new ConnectionDB();

      using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                  {
                      cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                      d.sql\_con.Open();
                      d.DR = cmbox.ExecuteReader();
      
                      try
                      {
                          while (d.DR.Read())
                          {
                              CmbRef\_Produit.Items.Add(d.DR\["Code\_article"\]).ToString();
                          }
      
                          //si le textbox est vide
                          if (string.IsNullOrWhiteSpace(CmbRef\_Produit.Text ))
                          {
                              // Message box
      
                              Lbl\_affich\_TxtQteStock.Text = "";
                              Lbl\_Affich\_Designation.Text = "";
                              Lbl\_Affich\_PrixUnitaire.Text = "";
                          }
      
                      }
                      catch (Exception ex)
      
      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      You need to show the code that uses the CONNECTER method.

      A 2 Replies Last reply
      0
      • L Lost User

        You need to show the code that uses the CONNECTER method.

        A Offline
        A Offline
        ago2486
        wrote on last edited by
        #3

        public partial class Form1 : Form
        {

            public Form1()
            {
                InitializeComponent();
        
            }
        

        ConnectionDB d = new ConnectionDB();

        using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                    {
                        cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                        d.CONNECTER.Open(); //\*\*\*\*i have an error here\*\*\*\*
                        d.DR = cmbox.ExecuteReader();
        
                        try
                        {
                            while (d.DR.Read())
                            {
                                CmbRef\_Produit.Items.Add(d.DR\["Code\_article"\]).ToString();
                            }
        
                            //si le textbox est vide
                            if (string.IsNullOrWhiteSpace(CmbRef\_Produit.Text ))
                            {
                                // Message box
        
                                Lbl\_affich\_TxtQteStock.Text = "";
                                Lbl\_Affich\_Designation.Text = "";
                                Lbl\_Affich\_PrixUnitaire.Text = "";
                            }
        
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
        
                            d.DECONNECTER.Close();
        
                        }
                    }
        
                }
        

        }

        1 Reply Last reply
        0
        • L Lost User

          You need to show the code that uses the CONNECTER method.

          A Offline
          A Offline
          ago2486
          wrote on last edited by
          #4

          public partial class Form1 : Form
          {

              public Form1()
              {
                  InitializeComponent();
          
              }
          

          ConnectionDB d = new ConnectionDB();

          using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                      {
                          cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                          d.CONNECTER();// i have an error here
                          d.DR = cmbox.ExecuteReader();
          
                          try
                          {
                              while (d.DR.Read())
                              {
                                  CmbRef\_Produit.Items.Add(d.DR\["Code\_article"\]).ToString();
                              }
          
                              //si le textbox est vide
                              if (string.IsNullOrWhiteSpace(CmbRef\_Produit.Text ))
                              {
                                  // Message box
          
                                  Lbl\_affich\_TxtQteStock.Text = "";
                                  Lbl\_Affich\_Designation.Text = "";
                                  Lbl\_Affich\_PrixUnitaire.Text = "";
                              }
          
                          }
                          catch (Exception ex)
                          {
                              MessageBox.Show(ex.ToString());
          
                              d.DECONNECTER();
          
                          }
                      }
          
                  }
          

          }

          L 1 Reply Last reply
          0
          • A ago2486

            public partial class Form1 : Form
            {

                public Form1()
                {
                    InitializeComponent();
            
                }
            

            ConnectionDB d = new ConnectionDB();

            using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                        {
                            cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                            d.CONNECTER();// i have an error here
                            d.DR = cmbox.ExecuteReader();
            
                            try
                            {
                                while (d.DR.Read())
                                {
                                    CmbRef\_Produit.Items.Add(d.DR\["Code\_article"\]).ToString();
                                }
            
                                //si le textbox est vide
                                if (string.IsNullOrWhiteSpace(CmbRef\_Produit.Text ))
                                {
                                    // Message box
            
                                    Lbl\_affich\_TxtQteStock.Text = "";
                                    Lbl\_Affich\_Designation.Text = "";
                                    Lbl\_Affich\_PrixUnitaire.Text = "";
                                }
            
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
            
                                d.DECONNECTER();
            
                            }
                        }
            
                    }
            

            }

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #5

            I am not sure that the sequence of commands is correct. Try this:

            using (ConnectionDB d = new ConnectionDB())
            {
            d.CONNECTER();

            using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
            {
                cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
            
                // remaining code
            }
            d.DECONNECTER();
            

            }

            A 2 Replies Last reply
            0
            • A ago2486

              public class ConnectionDB
              {

                  // Declaration des objets sql
                  public OleDbConnection sql\_con;
               
                  // declaration de la methode connecter
                  public void CONNECTER()
                  {
                      try
                      {
                          string connetionString = null;
                          //connection à la base de donnée avec mot de passe
                          connetionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Application.StartupPath + @"\\DB\_CaisseEnregistreuse.mdb;Persist Security Info=True;Jet OLEDB:Database Password=B@sta08091987";
                          sql\_con = new OleDbConnection(connetionString);
                          sql\_con.Open();
                          
                      }
                      catch (Exception ex)
                      {
                          MessageBox.Show("Erreur de connexion à la base donnée" + ex.ToString());
                      }
              
                      
                  }
              
                  // declaration de la methode deconnecter
                  public void DECONNECTER()
                  {
                      try
                      {
              
                          if (sql\_con.State == ConnectionState.Open)
                          {
              
                              sql\_con.Close();
                          }
                      }
                      catch (Exception ex)
                      {
                          MessageBox.Show("Erreur de deconnexion à la base donnée" + ex.ToString());
                      }
                  }
              

              public partial class Form1 : Form
              {

                  public Form1()
                  {
                      InitializeComponent();
              
                  }
              

              ConnectionDB d = new ConnectionDB();

              using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                          {
                              cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                              d.sql\_con.Open();
                              d.DR = cmbox.ExecuteReader();
              
                              try
                              {
                                  while (d.DR.Read())
                                  {
                                      CmbRef\_Produit.Items.Add(d.DR\["Code\_article"\]).ToString();
                                  }
              
                                  //si le textbox est vide
                                  if (string.IsNullOrWhiteSpace(CmbRef\_Produit.Text ))
                                  {
                                      // Message box
              
                                      Lbl\_affich\_TxtQteStock.Text = "";
                                      Lbl\_Affich\_Designation.Text = "";
                                      Lbl\_Affich\_PrixUnitaire.Text = "";
                                  }
              
                              }
                              catch (Exception ex)
              
              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #6

              First off, don't hard code connection strings - they need to be in a config file or similar, if only so you don't release the password in clear text with your app... Second, never store databases in your app directory: although it works in development, it will fail in production as the application folder rarely has write permissions anymore for anti-virus reasons. See here: Where should I store my data?[^] for some better ideas. Thirdly, you are much, much better off creating your Connection object in your code when you need it inside a using block, as they are scarce resources and should be Disposed when you are finished with them:

              using (SqlConnection con = new SqlConnection(strConnect))
              {
              con.Open();
              using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
              {
              cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
              using (SqlDataReader reader = cmd.ExecuteReader())
              {
              while (reader.Read())
              {
              int age = (int) reader["Age"];
              string desc = (string) reader["Description"];
              Console.WriteLine($"{age}\n{desc}");
              }
              }
              }
              }

              That way, whatever happens to your code, the objects will be closed and disposed for you automatically. Fourthly, although you are trying to separate the DB from the form (which is a good idea) don't use MessageBox to report problems with DB related stuff - it makes too many assumptions about how your code will be used. Error handling and reporting is the province of the Presentation Layer, not the Data Layer: there is no guarantee that the user will be able to see a MessageBox! Let the code that calls the DB stuff handle errors - it can report or not, but it may log instead, or just terminate what it is doing. Your way, the user gets the MessageBox, then your app crashes because the connection isn't open anyway.

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!<

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              A 2 Replies Last reply
              0
              • L Lost User

                I am not sure that the sequence of commands is correct. Try this:

                using (ConnectionDB d = new ConnectionDB())
                {
                d.CONNECTER();

                using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                {
                    cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                
                    // remaining code
                }
                d.DECONNECTER();
                

                }

                A Offline
                A Offline
                ago2486
                wrote on last edited by
                #7

                Thanks i will try it and you will get back

                1 Reply Last reply
                0
                • L Lost User

                  I am not sure that the sequence of commands is correct. Try this:

                  using (ConnectionDB d = new ConnectionDB())
                  {
                  d.CONNECTER();

                  using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                  {
                      cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                  
                      // remaining code
                  }
                  d.DECONNECTER();
                  

                  }

                  A Offline
                  A Offline
                  ago2486
                  wrote on last edited by
                  #8

                  I try and the error comes from me thank you very much mmister it works.

                  1 Reply Last reply
                  0
                  • OriginalGriffO OriginalGriff

                    First off, don't hard code connection strings - they need to be in a config file or similar, if only so you don't release the password in clear text with your app... Second, never store databases in your app directory: although it works in development, it will fail in production as the application folder rarely has write permissions anymore for anti-virus reasons. See here: Where should I store my data?[^] for some better ideas. Thirdly, you are much, much better off creating your Connection object in your code when you need it inside a using block, as they are scarce resources and should be Disposed when you are finished with them:

                    using (SqlConnection con = new SqlConnection(strConnect))
                    {
                    con.Open();
                    using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
                    {
                    cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                    while (reader.Read())
                    {
                    int age = (int) reader["Age"];
                    string desc = (string) reader["Description"];
                    Console.WriteLine($"{age}\n{desc}");
                    }
                    }
                    }
                    }

                    That way, whatever happens to your code, the objects will be closed and disposed for you automatically. Fourthly, although you are trying to separate the DB from the form (which is a good idea) don't use MessageBox to report problems with DB related stuff - it makes too many assumptions about how your code will be used. Error handling and reporting is the province of the Presentation Layer, not the Data Layer: there is no guarantee that the user will be able to see a MessageBox! Let the code that calls the DB stuff handle errors - it can report or not, but it may log instead, or just terminate what it is doing. Your way, the user gets the MessageBox, then your app crashes because the connection isn't open anyway.

                    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!<

                    A Offline
                    A Offline
                    ago2486
                    wrote on last edited by
                    #9

                    thank you sir message well received. I haven't tried the configuration file side for the connection to the database yet, but I will study it and see if I can manage it.

                    1 Reply Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      First off, don't hard code connection strings - they need to be in a config file or similar, if only so you don't release the password in clear text with your app... Second, never store databases in your app directory: although it works in development, it will fail in production as the application folder rarely has write permissions anymore for anti-virus reasons. See here: Where should I store my data?[^] for some better ideas. Thirdly, you are much, much better off creating your Connection object in your code when you need it inside a using block, as they are scarce resources and should be Disposed when you are finished with them:

                      using (SqlConnection con = new SqlConnection(strConnect))
                      {
                      con.Open();
                      using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
                      {
                      cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
                      using (SqlDataReader reader = cmd.ExecuteReader())
                      {
                      while (reader.Read())
                      {
                      int age = (int) reader["Age"];
                      string desc = (string) reader["Description"];
                      Console.WriteLine($"{age}\n{desc}");
                      }
                      }
                      }
                      }

                      That way, whatever happens to your code, the objects will be closed and disposed for you automatically. Fourthly, although you are trying to separate the DB from the form (which is a good idea) don't use MessageBox to report problems with DB related stuff - it makes too many assumptions about how your code will be used. Error handling and reporting is the province of the Presentation Layer, not the Data Layer: there is no guarantee that the user will be able to see a MessageBox! Let the code that calls the DB stuff handle errors - it can report or not, but it may log instead, or just terminate what it is doing. Your way, the user gets the MessageBox, then your app crashes because the connection isn't open anyway.

                      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt AntiTwitter: @DalekDave is now a follower!<

                      A Offline
                      A Offline
                      ago2486
                      wrote on last edited by
                      #10

                      public class ConnectionDB
                      {

                          // Declaration des objets sql
                          public OleDbConnection sql\_con;
                          public OleDbCommand sql\_cmd;
                          public OleDbDataAdapter DB;
                          public DataSet DS = new DataSet();
                          public DataTable DT = new DataTable();
                          public OleDbDataReader DR;
                          public string connetionString = null;
                      
                          // declaration de la methode connecter
                          public void CONNECTER()
                          {                           
                                  //connection à la base de donnée avec mot de passe
                                  connetionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + Application.StartupPath + @"\\DB\_CaisseEnregistreuse.mdb;Persist Security Info=True;Jet OLEDB:Database Password=B@sta08091987";
                                  sql\_con = new OleDbConnection(connetionString);
                          }
                      
                          // declaration de la methode deconnecter
                          public void DECONNECTER()
                          {
                              
                      
                                  if (sql\_con.State == ConnectionState.Open)
                                  {
                      
                                      sql\_con.Close();
                                  }
                              
                             
                          }
                      

                      public partial class Form1 : Form
                      {

                          public Form1()
                          {
                              InitializeComponent();
                      
                      
                      
                          }
                          ConnectionDB d = new ConnectionDB();
                      

                      private void LoadDB()
                      {
                      using (OleDbConnection sql_con = new OleDbConnection(d.connetionString))
                      {
                      sql_con.Open();
                      using (OleDbCommand sql_cmd = d.sql_con.CreateCommand())
                      {
                      string CommandText = "SELECT * FROM Detail_temp";
                      d.DB = new OleDbDataAdapter(CommandText, d.sql_con);
                      d.DS.Reset();
                      d.DB.Fill(d.DS);
                      d.DT = d.DS.Tables[0];
                      dataGridView1.DataSource = d.DT;
                      d.DECONNECTER();
                      }
                      }
                      }

                      private void Form1_Load(object sender, EventArgs e)
                      {

                              try
                              {
                                  
                                  LoadDB();
                                  d.sql\_con.Open();
                                  TxtQteCmd.Text = "1";
                                  Lbl\_Affich\_TotalCmd.Text = "0";
                                  LblAfficDate.Text = DateTime.Now.ToString(); 
                      
                                  using (OleDbCommand cmbox = d.sql\_con.CreateCommand())
                                  {
                                      cmbox.CommandText = "SELECT Code\_article FROM Catalogue";
                      
                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups