Good day everyone, dear blog readers. In today's article I will talk about accessing DBF files (tables) different ways. I encountered this problem when I needed to access FoxPro DBF tables. I tried through BDE, it didn’t work, only to Paradox tables (dbf), in the end I decided to try through the TDBF component - it also turned out to be a failure. I decided to try connecting via ADO the old fashioned way and everything went like clockwork.

Therefore, in this article I will tell you how you can connect to DBF tables in three ways:

  • Using BDE - for FoxPro tables I have this option I failed
  • Using ADO - FoxPro tables opened perfectly
  • Using the TDBF component, it opens Paradox tables with different encodings or dBase well.

To be honest, I can’t stand BDE at all, but I had to work with such tables and the first option through which I wanted to connect to them was to use BDE, which, in principle, it worked out for me, that is, I managed to get a list of tables, which I was happy about and thought that everything would go on as expected, but that was not the case. When I tried to connect to a table, I got an error something like:

I tried to install it both in the BDE Administrator itself and when connecting, but nothing worked. But using this method I was able to connect perfectly to DBF - Paradox tables, for example dBase.

Therefore, we install the following components on the form from the BDE tab:

  • TTable or TQuery
  • Optionally, you can TDataSource and TDbGrid

Next, in the DatabaseName property of the TDataBase component we set the name of the database, I wrote - MyDB, and in the DriverName property of the same component I selected STANDART from the drop-down list. We set the LoginPromt property to False, since there is no login and password on our tables. In the Params property we set the connection parameters, I only specified the path to our tables:

You can also double click Click on the TDataBase component and configure the necessary connection and set the Connected property to True, as a result, a connection to the tables should occur, without any errors. That's all, let's go to the TTable component, where in the DatabaseName property we indicate the name of our database, that is, MyDB. In the TableType property, select the table type, I specified ttDBase, and in the TableName property, select the table name, after which we set the Active property to True. That's it, it connects perfectly for me and displays the table just fine.

But this option did not work for me with FoxPro tables, as I mentioned above. Therefore, to solve my problem, I decided to use ADO technology. So from the ADO tab I installed the following components:

  • TADOConnection
  • TADOQuery or TADOTable
  • Optionally you can install TDataSource and TDBGrid

Next, we just need to create the connection that we made for the MS Access database, it will differ in that we select a different data provider, namely Microsoft Visual FoxPro ODBC. That's it, then we indicate the encoding and the path to the tables. If these are FoxPro tables, then the folder must contain a file with a list of all tables, extension *.dbc. That is, the connection string of the TADOCOnnection component will look something like this:

We connect the TADOConnection component with TADOTable or TADOQuery and work with the tables we need.

Another option is to work with dbf-format tables using the TDBF component, which I use in the project. To be honest, I want to abandon it, it just works well with encodings. I won’t tell you how to work with it, but I’ll just leave a link as an example.

Perhaps this code from can help:

The VB function you will need to put into MS Access is quite simple, and basically calls the TransferDatabase method, passing it the DSN (pointing to the source database), the source table name, and the destination table name. the code looks like this:

Public Function Import(dsnName As String, sourceTableName As String, targetTableName As String) ‘ if the table already existsm, delete it. On Error GoTo CopyTable DoCmd.DeleteObject acTable, targetTableName CopyTable: DoCmd.TransferDatabase _ acImport, _ "ODBC Database", _ "ODBC;DSN=" + dsnName, _ acTable, _ sourceTableName, _ targetTableName End Function

And then the C# code:

object accessObject = null; try ( accessObject = Activator.CreateInstance(Type.GetTypeFromProgID("Access.Application")); accessObject.GetType().InvokeMember("OpenCurrentDatabase", System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod, null, accessObject , new Object ( "AccessDbase.mdb" )); accessObject.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod, null, accessObject, new Object ( "Import", "DSN Name", "Source table name", "Target table name" )); accessObject.GetType().InvokeMember("CloseCurrentDatabase", System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod, null, accessObject, null); MessageBox.Show("Copy succeeded."); ) catch (Exception ex) ( string message = ex.Message; while (ex.InnerException != null) ( ex = ex.InnerException; message += "\r \n----\r\n" + ex.Message; ) MessageBox.Show(message); ) finally ( if (accessObject != null) ( System.Runtime.InteropServices.Marshal.ReleaseComObject(accessObject); accessObject = null; ) )

Changing VBA to read acLink rather than acImport should allow linking.

Edit comments

I can't help with this, but here is some VBScript that links a table from one MDB to another.

StrLinkFile = "C:\Docs\Link.mdb" strAccessFile = "C:\Docs\LTD.mdb" "Create Link..." Set cn = CreateObject("ADODB.Connection") cn.Open "Provider=Microsoft. Jet.OLEDB.4.0;" & _ "Data Source=" & strAccessFile & ";" & _ "Persist Security Info=False" Set adoCat = CreateObject("ADOX.Catalog") Set adoCat.ActiveConnection = cn Set adoTbl = CreateObject("ADOX.Table") Set adoTbl.ParentCatalog = adoCat adoTbl.Name = "LinkTable" adoTbl.properties("Jet OLEDB:Link Datasource") = strLinkFile adoTbl.properties("Jet OLEDB:Link Provider String") = "MS Access" adoTbl.properties("Jet OLEDB:Remote Table Name") = "Table1" adoTbl .properties("Jet OLEDB:Create Link") = True "Append the table to the tables collection " adoCat.Tables.Append adoTbl

Perhaps this code from can help:

The VB function you need to put in MS Access is quite simple, and basically calls the TransferDatabase method, passing it the DSN (pointing to the source database), the source table name, and the destination table name. the code looks like this:

Public Function Import(dsnName As String, sourceTableName As String, targetTableName As String) ‘ if the table already existsm, delete it. On Error GoTo CopyTable DoCmd.DeleteObject acTable, targetTableName CopyTable: DoCmd.TransferDatabase _ acImport, _ "ODBC Database", _ "ODBC;DSN=" + dsnName, _ acTable, _ sourceTableName, _ targetTableName End Function

And then the C# code:

object accessObject = null; try ( accessObject = Activator.CreateInstance(Type.GetTypeFromProgID("Access.Application")); accessObject.GetType().InvokeMember("OpenCurrentDatabase", System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod, null, accessObject , new Object ( "AccessDbase.mdb" )); accessObject.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod, null, accessObject, new Object ( "Import", "DSN Name", "Source table name", "Target table name" )); accessObject.GetType().InvokeMember("CloseCurrentDatabase", System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod, null, accessObject, null); MessageBox.Show("Copy succeeded."); ) catch (Exception ex) ( string message = ex.Message; while (ex.InnerException != null) ( ex = ex.InnerException; message += "\r \n----\r\n" + ex.Message; ) MessageBox.Show(message); ) finally ( if (accessObject != null) ( System.Runtime.InteropServices.Marshal.ReleaseComObject(accessObject); accessObject = null; ) )

Changing VBA to read acLink rather than acImport should allow linking.

Edit comments

I can't help with C#, but here's some VBScript that links a table from one MDB to another.

StrLinkFile = "C:\Docs\Link.mdb" strAccessFile = "C:\Docs\LTD.mdb" "Create Link..." Set cn = CreateObject("ADODB.Connection") cn.Open "Provider=Microsoft. Jet.OLEDB.4.0;" & _ "Data Source=" & strAccessFile & ";" & _ "Persist Security Info=False" Set adoCat = CreateObject("ADOX.Catalog") Set adoCat.ActiveConnection = cn Set adoTbl = CreateObject("ADOX.Table") Set adoTbl.ParentCatalog = adoCat adoTbl.Name = "LinkTable" adoTbl.properties("Jet OLEDB:Link Datasource") = strLinkFile adoTbl.properties("Jet OLEDB:Link Provider String") = "MS Access" adoTbl.properties("Jet OLEDB:Remote Table Name") = "Table1" adoTbl .properties("Jet OLEDB:Create Link") = True "Append the table to the tables collection " adoCat.Tables.Append adoTbl

DBF is a widely used data storage format that appeared in the 80s of the last century. The format was first used in the dBase DBMS family. Due to the popularity and widespread use of dBase, many dBase-like software products, collectively called xBase. Despite the considerable age of the format, it is still quite widely used. This article discusses how to work with DBF from 1C:Enterprise.

In 1C:Enterprise, a special software object, xBase, is used to work with files in the DBF format (version dBase III). Working with this object usually does not cause difficulties.

Attention!

When working with DBF files, remember that the file name must satisfy constraint 8.3.

Attention!

The xBase object is available on both the client side and the server side. You should think through client-server interaction when solving each specific problem.

Reading a DBF File

Reading data from a DBF file is performed in several successive steps:

  1. Creating an XBase object;
  2. Opening a file;
  3. Sequentially iterate through all lines of the file and read field values;
  4. Closing the file.
DBP = New XBase; DBP. OpenFile("D:\MyFile.dbf" ); // Stage 2. Opening the file While the Truth Cycle // Stage 3. Looping through the lines of the file Report(DBF.NAME); If NOT DBP. Next() Then // Position on next record Abort; endIf; EndCycle; DBP. CloseFile(); // Stage 4. Closing the file

You can use a slightly modified algorithm for iterating over the lines of a file:

NOT DBF yet. AtEnd() Loop Report (DBF.NAME); DBP. Next(); EndCycle;

Uploading to a DBF file

Stages of uploading to a DBF file:

  1. Creating an XBase object;
  2. Specifying the encoding (if not specified, ANSI encoding will be used);
  3. Description of fields;
  4. File creation;
  5. Loop with adding and filling lines;
  6. Closing the file.

Let's look at this process using an example:

DBP = New XBase; // Stage 1. Create an XBase object DBP. Encoding = EncodingXBase. OEM; // Stage 2. Specifying the encoding DBP. Fields. Add("CODE" , "S" , 9 ); // Stage 3. Description of the field name and type DBP. Fields. Add("NAME" , "S" , 40 ); DBP. CreateFile("D:\MyFile.dbf" ); // Stage 4. File creation Selection = Directories. Nomenclature. Choose(); Bye Selection. Next() Loop DBP. Add(); // Add a line DBP. CODE = Sample. Code; // Fill in the field value DBP. NAME = Selection. Name; DBP. Write(); // Write the line EndCycle; DBP. CloseFile(); // Stage 6. Closing the file

When specifying the encoding, the XBase Encoding type is used, which can take two values:

  • ANSI– Windows format;
  • OEM– DOS format.

Adding a new field when describing a structure has the syntax

Add (< Имя>, < Тип>, < Длина>, < Точность>)

The following types are available:

  • “N” – number;
  • “S” – string;
  • “D” – date;
  • “L” – boolean;
  • “F” – similar to “N” – number.

The field length is required for the "N", "F" and "S" field types.

Working with Indexes

An index file may be used in conjunction with the DBF file, which may contain information about one or more indexes. The presence of indexes makes it possible to use search, and not just sequential search of all lines of the file.

When creating an index file, you must specify:

  • List of indices;
  • Path to save the index file (at stage 4 of upload).

Example of creating an index file:

DBP . Indexes. Add("INDCODE" , "CODE" ); DBP. CreateFile("D:\MyFile.dbf" , "D:\index.cdx" );

The syntax for adding a new index is:

Add (< Имя>, < Выражение>, <Уникальность>, < Убывание>, < Фильтр >)

To use indexes when reading from a DBF file:

  • Specify the path to the index file (at stage 2 of the download);
  • Set the current index.

Example of opening a DBF file using an index file:

DBP . OpenFile("D:\MyFile.dbf" , "D:\index.cdx" ); DBP. CurrentIndex = dbf. Indexes. INDCODE;

Attention!

When opening a DBF file, positioning occurs on the first record in the file. The first entry in the file does not match the first entry in the index. Because of this, when using indexes, you must position yourself on the first row of the index before traversing rows sequentially. This can be done using the First() method, for example:

DBP. First();

One of two functions can be used to search:

  • Find (< Ключ>, < Режим >) ;
  • FindByKey(< Режим >) .

As a result of both functions, a value of type Boolean is returned (whether a record with the specified conditions was found or not). If the search is successful, the current pointer is set to the found line. One of the following values ​​can be used as the search mode:

  • «>=»;
  • «>»;
  • «<=»;
  • «<«.

Let's look at searching in a DBF file using examples:

DBP = New XBase; DBP. OpenFile("D:\MyFile.dbf" , "D:\index.cdx" ); // When opening a DBF file, an additional index file is specified DBP. CurrentIndex = dbf. Indexes. INDCODE; // Set the current index // search using the Find method: If DBP. Find("000000003" , "=" ) Then Report( + DBP. NAME); Else Report("Not found"); endIf; // search using the FindByKey method: DBP. Key. CODE = "000000002" ; If DBP. FindByKey("=" ) Then Report( "Found. Item name: "+ DBP. NAME); Else Report("Not found"); endIf; DBP. CloseFile();

Deleting entries in a DBF file

Deleting a record is done using the Delete () method:

DBP . Delete();

But when using this method, the record is not permanently deleted from the file; it is marked as deleted. When iterating over rows, records marked for deletion are skipped. If you want to crawl the entire file, including entries marked for deletion, you must set the property to True. DisplayDeleted xBase object. You can find out whether a record is marked for deletion or not using the RecordDeleted() function. To remove the deletion mark, use the Restore() method.

DBP . DisplayDeleted = True; NOT DBF yet. AtEnd() Loop If DBP. RecordDeleted() Then DBP. Restore(); endIf; DBP. Next(); EndCycle;

To directly remove marked entries, use the Shrink() method:

DBP . Compress();

If you need to delete all entries in a file directly, you can use the ClearFile() method:

DBP . ClearFile();

Loading from DBF using ADO

ADO technology can be used to work with DBF files. ADO drivers are included in the Windows operating system and do not need to be installed additionally.

Let's look at an example of code for reading from a DBF file using ADO technology:

ADO = New COMObject("ADODB.Connection" ); // Create a COM object ADO. Open( "Provider=Microsoft.Jet.OLEDB.4.0; |Data Source=""D:\""; |Extended Properties=DBASE III"); DB = ADO. Execute("Select * from MyFile" ); // request to get all records from the MyFile.DBF file Bye BD. EOF= 0 Cycle //Loop through DBF file records Report(DB. Fields("Name" ). value); // Example of accessing a field value DB. MoveNext(); //Go to the next entry EndCycle; ADO. Close();

The example shown uses the connection string "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="D:\";Extended Properties=DBASE III". In this line:

  • Provider is the driver used;
  • Data Source – path where the DBF file is located. The path is specified accurate to the directory. The file name is used as the table name in queries;
  • Extended Properties – when accessing DBF files, this is a required parameter. You can specify the file format

Attention!

When reading using the specified method, the default encoding is OEM. In order to change the encoding to ANSI, you need to set the HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Jet\4.0\Engines\xBase\DataCodePage parameter to “ANSI” in the Windows registry.

Today, probably, no one needs to be told that quite often many users encounter files with the .dbf extension. The saddest thing is that in Windows OS, even if Microsoft Office is installed, not a single program is associated with this file type. We have it, we will now try to figure it out. At the same time, let's see how you can set an extension association for subsequent automatic data recognition and opening the desired file.

DBF format: description

Actually, from the very abbreviation applied to the extension of a file of this type, one can already conclude that this is a database. It is somewhat specific, since such files usually have the extension

In this case, we have another one, which, however, despite its specificity, is recognized by many programs that support working with information of this type. This can be the same Excel or Access, which are part of the main Microsoft Office package, or any other office applications from third-party developers.

How to open DBF in the standard version

In fact, if you suddenly come across a file of this type (the icon is not used on it even in Explorer), do not panic. It can be opened quite simply using Excel, since it is in it that the entire logical structure is saved and, taking into account the same, the possibility of using a standard search system.

Since no program is associated with the file itself in the standard version, there are two ways to proceed. It is recommended, for example, to simply launch Excel or Access, and then use the standard file opening menu or the Ctrl + O key combination. However, in the menu that appears in the file type field, you should specify “All files” (and not the “native” format), after why select the file you are looking for. Rest assured: any spreadsheet program will recognize this data type without any problems.

As is already clear, the problem of how to open a DBF file in our case comes down only to using a standard office application in manual mode. As is already clear, this method is not always convenient and requires a certain amount of time.

Related programs

Now let's look at the DBF file itself. How can I open it without using standard office suite programs? Yes, by the same utilities included in similar software products.

For example, it could be the same Open Office, Lotus, etc. In principle, there is not much difference here, since the only thing that matters is that the program used is capable of working with tabular electronic data. Reading the DBF format is done exactly the same in all cases. By the way, this does not depend on the developer of the office suite, since everyone has support for this type of data, including even platforms like Oracle.

Changing default opening options

Now let's see how to open DBF files so that automatic mode is used. In the simplest case, this is done from the submenu called up by right-clicking on the file in the usual “Explorer”, where the “Open with...” command is selected.

For a single case, one of the applications listed is used. In order not to rack your brain again about how to open DBF files, you can simply specify the selected application, and then check the box next to the line “Use for all files of this type” at the bottom. The same Excel in the future (if it is selected as the default program) will open a file of this type with a regular double click.

It goes without saying that instead of Excel, you can choose Access or other programs that can recognize and open this type of data. That's not the point. The main thing is to configure automatic opening of the database. Well, what to work with in terms of software is up to each individual user of the computer system.

What's the result?

To summarize, it is worth saying that the best option when opening files of this type is, naturally, the office suite from Microsoft Corporation, since it is the most widespread all over the world. True, there is nothing wrong with the fact that a user who does not use Microsoft products will open data of this type in any other application.

As is already clear from all of the above, table editors are present in almost all packages known today. They may differ from each other only in their names, and certainly not in their functional set, which, as a rule, is the same everywhere, with rare exceptions.

Among other things, accordingly, you can use many development tools using a fairly large number of programming languages. On the same platform that supports the creation and optimization of SQL servers, such files are opened, as they say, instantly. When opened, they will have a rather specific appearance, which is somewhat unusual for the average user. However, most users are unlikely to use such professional development tools and will limit themselves only to a standard software set.