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. Problem connecting to an Access database

Problem connecting to an Access database

Scheduled Pinned Locked Moved C#
helpdatabasedesign
8 Posts 2 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.
  • T Offline
    T Offline
    TheBlindWatchmaker
    wrote on last edited by
    #1

    Greetings! I'm trying to connect to a database and read certain fields from it. I'm unable to read any fields from it and would appreciate your help debugging/fixing the problem. Here is what I have: 1. A file that acts has the database interface code: public class AppDatabaseInterface { // Directory names private string m_cstrDefaultdbDir = "C:\\"; // File names private const string m_cstrDBFileName = "DefaultDatabase.mdb"; private System.Data.OleDb.OleDbConnection m_dbConn; public AppDatabaseInterface() { // Determine the App Root directory when this object is constructed System.Reflection.Assembly assm = System.Reflection.Assembly.GetAssembly(System.Type.GetType("AppDatabase.AppDatabaseInterface")); m_cstrDefaultdbDir = System.IO.Path.GetDirectoryName(assm.CodeBase.ToString()); m_cstrDefaultdbDir = m_cstrDefaultdbDir.Remove(0, 6); // Removes the leading file:\ header from the path. OpenDatabase(); } private void OpenDatabase() { lock (this) { // If the database connection hasn't been initialized, create it. // If it exists and is currently connected, close the connection // as we are about to establish a new connection. if (m_dbConn == null) { m_dbConn = new OleDbConnection(); } else { if (m_dbConn.State != ConnectionState.Closed) { m_dbConn.Close(); } } // Create the new connection string and try and attach to the new database. try { m_dbConn.ConnectionString = string.Format( @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}\{1};", m_cstrDefaultdbDir, m_cstrDBFileName); } catch { Console.WriteLine("Could not open database"); } m_dbConn.Open(); } } 2. The actual UI form public partial class frmAppDatabase: Form { AppDatabaseInterface m_database; public frmSpeakerDatabase() { InitializeComponent()

    G 1 Reply Last reply
    0
    • T TheBlindWatchmaker

      Greetings! I'm trying to connect to a database and read certain fields from it. I'm unable to read any fields from it and would appreciate your help debugging/fixing the problem. Here is what I have: 1. A file that acts has the database interface code: public class AppDatabaseInterface { // Directory names private string m_cstrDefaultdbDir = "C:\\"; // File names private const string m_cstrDBFileName = "DefaultDatabase.mdb"; private System.Data.OleDb.OleDbConnection m_dbConn; public AppDatabaseInterface() { // Determine the App Root directory when this object is constructed System.Reflection.Assembly assm = System.Reflection.Assembly.GetAssembly(System.Type.GetType("AppDatabase.AppDatabaseInterface")); m_cstrDefaultdbDir = System.IO.Path.GetDirectoryName(assm.CodeBase.ToString()); m_cstrDefaultdbDir = m_cstrDefaultdbDir.Remove(0, 6); // Removes the leading file:\ header from the path. OpenDatabase(); } private void OpenDatabase() { lock (this) { // If the database connection hasn't been initialized, create it. // If it exists and is currently connected, close the connection // as we are about to establish a new connection. if (m_dbConn == null) { m_dbConn = new OleDbConnection(); } else { if (m_dbConn.State != ConnectionState.Closed) { m_dbConn.Close(); } } // Create the new connection string and try and attach to the new database. try { m_dbConn.ConnectionString = string.Format( @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}\{1};", m_cstrDefaultdbDir, m_cstrDBFileName); } catch { Console.WriteLine("Could not open database"); } m_dbConn.Open(); } } 2. The actual UI form public partial class frmAppDatabase: Form { AppDatabaseInterface m_database; public frmSpeakerDatabase() { InitializeComponent()

      G Offline
      G Offline
      Guffa
      wrote on last edited by
      #2

      TheBlindWatchmaker wrote:

      However, I see nothing.

      You see nothing? Not even the error message? You are trying to use the property "Makes", but you have not created any property with that name. What do you expect to happen?

      --- b { font-weight: normal; }

      T 1 Reply Last reply
      0
      • G Guffa

        TheBlindWatchmaker wrote:

        However, I see nothing.

        You see nothing? Not even the error message? You are trying to use the property "Makes", but you have not created any property with that name. What do you expect to happen?

        --- b { font-weight: normal; }

        T Offline
        T Offline
        TheBlindWatchmaker
        wrote on last edited by
        #3

        Oops! My mistake! Here's the "Makes" method in the AppDatabaseInterface.cs file public string[] Models(string make) { { OleDbDataReader dbr = null; ArrayList Models = new ArrayList(); OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM {0};", "Speakers"), m_dbConn); //OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM {0} WHERE {1} = {2};", "Speakers", "MAKE", make), m_dbConn); dbr = cmd.ExecuteReader(); // Read each record one at a time ... while (dbr.Read()) { // Load our arrays with the Field names // and values. string dbMake = ""; string model= ""; for (int it = 0; it < dbr.FieldCount; it++) { string strField = dbr.GetName(it); if (strField == "MAKE") { dbMake = (string)dbr.GetValue(it); } if (strField == "MODEL") { model = (string)dbr.GetValue(it); } } if (dbMake == make) Models.Add(model); } string[] strModels = new string[Models.Count]; int i = 0; foreach (object o in Models) { strModels[i++] = (string)o; } return strModels; } } Thanks!

        G 1 Reply Last reply
        0
        • T TheBlindWatchmaker

          Oops! My mistake! Here's the "Makes" method in the AppDatabaseInterface.cs file public string[] Models(string make) { { OleDbDataReader dbr = null; ArrayList Models = new ArrayList(); OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM {0};", "Speakers"), m_dbConn); //OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM {0} WHERE {1} = {2};", "Speakers", "MAKE", make), m_dbConn); dbr = cmd.ExecuteReader(); // Read each record one at a time ... while (dbr.Read()) { // Load our arrays with the Field names // and values. string dbMake = ""; string model= ""; for (int it = 0; it < dbr.FieldCount; it++) { string strField = dbr.GetName(it); if (strField == "MAKE") { dbMake = (string)dbr.GetValue(it); } if (strField == "MODEL") { model = (string)dbr.GetValue(it); } } if (dbMake == make) Models.Add(model); } string[] strModels = new string[Models.Count]; int i = 0; foreach (object o in Models) { strModels[i++] = (string)o; } return strModels; } } Thanks!

          G Offline
          G Offline
          Guffa
          wrote on last edited by
          #4

          TheBlindWatchmaker wrote:

          Here's the "Makes" method in the AppDatabaseInterface.cs file

          No, it isn't.

          --- b { font-weight: normal; }

          T 1 Reply Last reply
          0
          • G Guffa

            TheBlindWatchmaker wrote:

            Here's the "Makes" method in the AppDatabaseInterface.cs file

            No, it isn't.

            --- b { font-weight: normal; }

            T Offline
            T Offline
            TheBlindWatchmaker
            wrote on last edited by
            #5

            Damnit! I'm really inept today! Apologies, apologies! This might be it! :) public string[] Makes { get { OleDbDataReader dbr = null; ArrayList Makes = new ArrayList(); OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM {0};", "Speakers"), m_dbConn); dbr = cmd.ExecuteReader(); // Read each record one at a time ... while (dbr.Read()) { // Load our arrays with the Field names // and values. NOTE: Reloading the field // names over and over again is probably // redundant, but I'm not sure that the order // column names are returned is fixed. for (int it = 0; it < dbr.FieldCount; it++) { string strField = dbr.GetName(it); if (strField == "MAKE") { string make = (string)dbr.GetValue(it); bool found = false; foreach (object o in Makes) { if ((string)o == make) { found = true; break; } } if (found) Makes.Add(make); break; } } } string[] strMakes = new string[Makes.Count]; int i= 0; foreach (object o in Makes) { strMakes[i++] = (string)o; } return strMakes; } }

            G 1 Reply Last reply
            0
            • T TheBlindWatchmaker

              Damnit! I'm really inept today! Apologies, apologies! This might be it! :) public string[] Makes { get { OleDbDataReader dbr = null; ArrayList Makes = new ArrayList(); OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM {0};", "Speakers"), m_dbConn); dbr = cmd.ExecuteReader(); // Read each record one at a time ... while (dbr.Read()) { // Load our arrays with the Field names // and values. NOTE: Reloading the field // names over and over again is probably // redundant, but I'm not sure that the order // column names are returned is fixed. for (int it = 0; it < dbr.FieldCount; it++) { string strField = dbr.GetName(it); if (strField == "MAKE") { string make = (string)dbr.GetValue(it); bool found = false; foreach (object o in Makes) { if ((string)o == make) { found = true; break; } } if (found) Makes.Add(make); break; } } } string[] strMakes = new string[Makes.Count]; int i= 0; foreach (object o in Makes) { strMakes[i++] = (string)o; } return strMakes; } }

              G Offline
              G Offline
              Guffa
              wrote on last edited by
              #6

              I see. The method does exactly what it should, and returns an empty array. You only add to the ArrayList duplicates of values that already exist in the list, but as you start with an empty list, there are never any duplicates, so it will always remain empty. I guess that your intention was to add the values that aren't duplicates? In that case, why don't you just get the unique values from the database in the first place? And if you specify what field you want instead of using "select *", you don't have to loop through the fields looking for the one you want.

              --- b { font-weight: normal; }

              T 1 Reply Last reply
              0
              • G Guffa

                I see. The method does exactly what it should, and returns an empty array. You only add to the ArrayList duplicates of values that already exist in the list, but as you start with an empty list, there are never any duplicates, so it will always remain empty. I guess that your intention was to add the values that aren't duplicates? In that case, why don't you just get the unique values from the database in the first place? And if you specify what field you want instead of using "select *", you don't have to loop through the fields looking for the one you want.

                --- b { font-weight: normal; }

                T Offline
                T Offline
                TheBlindWatchmaker
                wrote on last edited by
                #7

                Hi Guffa, The Makes field has, say, 10 speakers from Mfr1, 10 from Mfr2 etc. I want the combo box to show Mfr1, Mfr2 and so on. How would you suggest I do this? Thanks for your time!

                G 1 Reply Last reply
                0
                • T TheBlindWatchmaker

                  Hi Guffa, The Makes field has, say, 10 speakers from Mfr1, 10 from Mfr2 etc. I want the combo box to show Mfr1, Mfr2 and so on. How would you suggest I do this? Thanks for your time!

                  G Offline
                  G Offline
                  Guffa
                  wrote on last edited by
                  #8

                  Select only the field containing the data that you want, and use the distinct keyword to get only one of each value.

                  --- b { font-weight: normal; }

                  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