Dbf to mysql linux

DBF в MySQL: Как я конвертировал ФИАС.

Добрый день, уважаемый читатель!

Вот, как всегда мне достаются весьма увлекательные задачи. В этот раз нужна была база улиц Челябинска и Казани. Те кто с подобным сталкиваются наверняка слышали о КЛАДР-е. Это такой себе список городов, улиц и т.д. Но он к 2011 году успел устареть морально и в плане разработки его забросили. К слову, тот же самый разработчик решил начать с чистого листа и в 2011г, и по текущее время разрабатывает базу ФИАС. База большая, архив 2ГБ, в распаковке около 10Гб. И вот я решил загнать всю эту базу в MySQL. Заодно скилы подтянуть. В дополнение ко всему единственный нормальный конвертер dbf2mysql для линукса поддерживает кодировку только latin1.

Выкладывают эту базу на сайте Федеральной Налоговой Службы(ФНС)
Выкладывают ее там в формате DBF и XML. Мы будем работать с DBF.

Итого, имеем платформу Debian GNU\Linux на 8-ядерном сервере, 12Гб ОЗУ и базу данных разбитую файликами на 10Гб в формате DBF.

Сам скрипт конвертации вышел таким вот:
indir — директория в которой лежат файлы DBF и DBT. Скрипт по ней проходит, по всем файлам, после обработки удаляет. Если не нужно удаление, просто удалите в строке rm /tmp/$table.out.sql&rm /tmp/$table.outtmp.sql&rm $file

Делаем его исполняемым:

Немного объяснений. Скрипт смотрит все файлики в папке indir с расширением postfix и уже идя по циклу:

  1. Дергает название файла. Удаляет расширение. Удаляет prefix, в нашем случае это часть пути «./».
  2. Конвертирует файл заливая в MySQL, в таблицу с названием из п.1
  3. Делает дамп таблицы в папку /tmp с названием таблицы и расширением .sql
  4. Меняет кодировку в файле с cp866 в utf-8
  5. Меняет кодировку в дамп-файле таблицы
  6. Удаляет такую таблицу если она уже есть, а она есть, это следует из п.2
  7. Загоняет дамп в таблицу с именем из п.1., но уже в нужной кодировке.
  8. Удаляет временные файлы

Ну вот собственно и вся казалось бы конвертация. Но естественно скрипт работает в 1 поток всего, и достаточно медленно. Если у вас маленькая база данных, то думаю дальше можете не читать.

Чтобы как-то все это чудо ускорить и разделить, мы создадим и примонтируем раздел в памяти ОЗУ. Своп я сразу отключил, чтобы видеть ограничения по памяти.

mkdir /mnt/ramdisk1
mkdir /mnt/ramdisk2
mkdir /mnt/ramdisk3
mkdir /mnt/ramdisk4

mount -t tmpfs -o size=1024M tmpfs /mnt/ramdisk1
mount -t tmpfs -o size=1024M tmpfs /mnt/ramdisk2
mount -t tmpfs -o size=1024M tmpfs /mnt/ramdisk3
mount -t tmpfs -o size=1024M tmpfs /mnt/ramdisk4

Дальше я скопировал файл конвертации, он у меня лежит в поддиректории converter в каждый из этих временных разделов. Выше уровнем скопировал по несколько файлов. После чего выполнил команды

Либо, если хотите наблюдать за процессом, как я в screen, в каждом собственном окне запустил отдельно каждую команду:

Но это уже дело вкуса.

Все, файлики работают в фоне и каждый гребет данные из своей папки. Естественно конвертировать ФИАС 4Гб ОЗУ не хватит, но тут я решил не рисковать и просто потом закинуть еще файлы и запустить скрипты повторно.

Источник

Из dbf в MySQL и обратно. Производственная драма с прологом, но без эпилога

Евгений Чайкин aka StraNNik

24 December 2008 г

На новой работе большая часть времени уходит на работу с базой данных. База большая, хаотичная и в целом — внушает ужас. Увы, отнюдь не объёмами, но скорее качеством данных.

Дабы вы поняли всю прелесть и пикантность ситуации, добавлю — база мало того, что неиндексированная, так ещё и с отсутствующим ключевым полем.

Читайте также:  Linux load module modprobe

Хранится всё это Щастье в dbf. Разного рода вспомогательные базы, базочки, базюшечки и просто обновления — в том же dbf.

Поскольку с dbf я дружу слабо, а с MySQL — средне, было принято решение — «загнать эту . базу в мускуль, а там видно будет». Как это ни смешно, решение оказалось правильным. С другой стороны, есть подозрение, что правильным было бы любое решение, потому что один из принятых в этой конторе методов обработки информации заключался в «распечатать всё, а потом силами нескольких человек найти нужное в распечатках, а потом вручную вбить обратно».

Заканчивая лирическое отступление, расскажу — как я загоняю dbf-ки в MySQL и потом выковыриваю их обратно.

aptitude search навёл меня на утилиту dbf2mysql

Я не буду пересказывать здесь ман, вскользь отмечу только, что ключ «перевести имена полей в нижний регистр» работает, а вот «перевести значения полей в нижний/верхний регистр» — не работает.

У утилиты этой есть один, но существенный на мой взгляд недостаток. Автор её и слыхом не слыхивал о существовании кодировок, отличных от latin1. В результате имеем таблицу в кодировке latin1, набитую данными в кодировке CP866.

Но нас таким не напугаешь. Возможно кто-то применит секретное заклинание alter table, сменит тип данных с текстового на blob, выправит кодировку, а потом сменит тип данных обратно, но это не мой путь. Этих самых полей у меня — неисчислимое множество (ну вру. Исчислимое, что уж там. Но всё равно — много).

Выручает старый-добрый mysqldump с принудительным выставлением кодировки в latin1.

Обрабатываем полученный файл напильником iconv’ом, перегоняя из CP866 в юникод, меняем в нём кодировку с latin1 на utf8, drop-аем таблицу, загоняем дамп обратно в мускуль — et voila!

Дабы работать было удобнее, добавляю отдельное поле типа int, заполняю его автоинкрементом и индексирую по нему. Иначе — совсем грустно. Но это уже сугубо моя локальная специфика.

Самое интересное начинается, когда приходит время загнать данные из MySQL обратно в dbf. Вот тут уже — чистое шаманство. Вышеупомянутая утилита dbf2mysql имеет и оборотную сторону mysql2dbf. И даже вроде как работает, но. Но о кодировках, отличных от latin1 можно забыть.

Но настоящего джедая не напугать такими мелочами. Берём, делаем выборку из MySQL, посредством INTO OUTFILE формируем csv, открываем готовую dbf-ку с нужной структурой редактором dbf от pssoft.ru (спасибо автору), удаляем все данные и импортируем туда данные из csv. Одно уточнение — данные в csv должны быть в CP1251, но это такие мелочи.

От счастливого финала нас отделяет только N-ное количество щелчков мышью. Каждое поле dbf-а нужно сопоставить полю csv-шки. Автоматизировать — никак. У меня таких полей — 70.

Клик-клик-клик.
Клик-клик-клик.
Клик-клик-клик.

ДААА! Экспорт в dbf и вожделенный файлик на диске, будь он неладен.

К чему всё это? К тому, что если кто знает способ лучше — я просто изнемогаю от желания его узнать. А пока тихо радуюсь, что результаты обработки в 90% случаев нужны не в dbf, а в xls, получить который из csv — дело пары минут.

Комментарии

Страницы комментариев: 1 :: 2 :: следующая

Источник

Is an easy way to import .dbf file contents into MySQL in terminal

I’ve got this files:

I want to do but in the terminal. any idea?

thanks to roadmr: this is how I did it.

after that checked on MySQL.

3 Answers 3

I found a «dbf2mysql» package:

This program takes an xBase file and sends queries to an MySQL server to insert it into an MySQL table and vice versa.

I haven’t tried it myself but it looks like it will do what you need. To install (and since you seem to be handy with the terminal):

There is a dbf2mysql tool in the Ubuntu software repositories. I never used it, but from the description it seems to do what you want?

Читайте также:  Mouse dpi windows sensitivity

An important thing to note is that, as stated in the man page:

mysql2dbf can’t write MEMO files at this time.

The other day, I converted one file using dbf2mysql and thought my problems with this were over. Unfortunately, I then spent the next 6 hours trying to resolve the issue of one of my largest files failing to be written into MySQL.

There were no errors thrown at all, it simply wouldn’t write. I went through a plethora of steps, including changing the buffer size, etc. to no avail, before realising that it was a MEMO file.

I’m new to all of this, so in order to help other newbies out I’ll let you in on the secret. The only way to know that you are dealing with a MEMO file, as produced by Visual FoxPro (as far as I know, anyway) is that it has 3 companion files ending with .cdx (which they all have), .dbt , and .fpt .

  • .dbf = The database file you are trying to convert, of course.
  • .cdx = A type of compound index file.
  • .dbt = Contains the MEMO text itself, but could not be opened with a text editor.
  • .fpt = Contains the MEMO header record.

I was fortunate enough to have one with only 2 of the 3 companion files, .fpt and .cdx . which DID convert. So, through the process of elimination, it is the .fpt file, or MEMO header record, which is the offending file. Simply moving that file out of the directory doesn’t work, unfortunately.

I’m sure there is a way around it, unfortunately I don’t know which yet. However, when (and I do mean ‘when’) I resolve this, I’ll post it here.

Источник

DBF to MySQL

[About Migration] [FAQ] [Tutorial] [Release Notes] [Download] [Buy]
Latest version 5.5 released 02/05/2020

DBF to MySQL converter is a program to migrate FoxPro, DBase or Clipper (*.dbf) databases to MySQL, MariaDB and Percona server. The program has high performance due to direct connection to source and destination databases (it does not use ODBC or any other middleware software). Command line support allows to script, automate and schedule the conversion process.

Features

  • All formats of FoxPro data and MEMO files are supported
  • All versions of Linux/Unix and Windows MySQL servers are supported
  • High performance due to direct connection to source and destination databases (the program does not use ODBC or any other middleware software)
  • Option to customize resulting table structure
  • Special approach for Virtual Server users
  • Option to specify MySQL charset and engine type
  • Support for large .dbf files (4GB+)
  • Option to merge DBF data into an existing MySQL database
  • Option to export DBF data into MySQL dump file
  • All FoxPro encodings are supported
  • Verified compatibility with MariaDB and Percona
  • Stores conversion settings into profile
  • Quick Launch
  • Command line support
  • Easy-to-use wizard-style interface
  • Full install/uninstall support
  • The product can be customized according to customer requirements
  • Unlimited 24/7 support service
  • 1-year subscription for updates

Limitations

  • Does not convert indexes
  • Demo version converts only 50 records per table

Requirements

  • Supported OS: Windows XP(SP2 or SP3)/Vista/7/8/10, Server 2003/2008/2012/2016, Linux with WINE

Virtual Server users option

If you are using Virtual Server hosting you probably have no sufficient privileges to create new databases on the target MySQL server. For this case we recommend the following approach:

  1. ask your Virtual Server administrator to create blank database for you
  2. run DBF to MySQL converter and select this database as the conversion target
  3. click «Yes» when you will be asked if you’d like to overwrite existing MySQL database

When you complete these steps, the entire contents of the source MS Access database will be imported into the specified MySQL database.

MySQL dump file

DBF to MySQL converter allows users to export FoxPro database into a local script file instead of moving it to MySQL server directly. The resulting file contains MySQL statements to create all tables and to fill them with the data. Click here to learn how to import MySQL dump file into the database.

Customize table structure

Manual table structure customization can be accessed by double click on the corresponding table name in «Selected tables» list of «Step 4 of 6» wizard page.

To customize type mapping select the appropriate item in the listview on the left and specify new name, type and default value for the field using «Field info» group of controls. Please note that listview on the left contains column attributes of the original types mapping, new custom types and attributes will be displayed in «Field info» controls when the corresponding item is highlighted in the listview.

Once you stored conversion settings into profile you can run the program in Quick Launch mode. Just launch Windows Explorer and double-click on the profile description (.d2s) file with left mouse button. This will cause DBF to MySQL wizard to launch conversion loading the necessary settings from the specified profile. Then you will be taken right to the screen with progress of conversion without entering all conversion settings.

Try before you buy

Still not sure the program fits your needs? Try free demo version with limited features. It will allow you to convert only 50 records for each database table. Test the quality of the demo and come back to place an order if satisfied with the results.

Intelligent Converters software is distributed through downloading from the official server only. For online credit card purchasing select the desired software package in the table below and click the corresponding BUY NOW link. To learn about alternative payment options, visit Ordering Page. DBF to MySQL converter is covered by 30 day money-back guarantee

Источник

Easiest way to continually import data to MySQL from a dbf file on my local computer

I have a problem that has been annoying me for quite some time now and a few days ago I started googling for a solution, but I haven’t really gotten anything to work. I’ve read a little about something called SSIS, but I’m not sure it does what I’m looking for or if there is something else I should research in order to accomplish my goal. This is my problem:

My accounting program produces and updates a .dbf file with information about all vouchers and places it in a folder on my local computer. Our MySQL must continually be updated with this information. So this is what I do twice a day:

  • I open up the .dbf file in excel
  • Save it as a .csv.
  • Close Excel
  • Open the file in notepad++
  • Convert the formating to utf8
  • Save
  • log in to MySQL
  • Go to the right table
  • Upload the .csv
  • Replace the old data with the new

As this takes quite a bit of time, I feel that there must be better ways to do this. It would be great if I could have this scheduled to be done automatically or if there is some kind of an SQL query that could do this, because then I could use PHP to make a website that I could enter and have the query run when I press a button or something.

So my question is: What is the most simple way to continually get the info from the .dbf file into my SQL server?

Источник

Читайте также:  Дрова для windows server
Оцените статью