script1adsense2code
script1adsense3code
Установка и настройка
Импорт и экспорт данных между MySQL и Excel стал намного проще в Excel 2007, чем в предыдущих версиях. Чтобы изучить эту функцию, вам нужно установить MySQL для Excel.
Вы можете установить компонент MySQL для Excel при установке MySQL Community Server 6. Или вы можете установить его как дополнение к существующей установке MySQL Server. Однако для установки этого компонента есть некоторые предпосылки.
MySQL для Excel Требования
Для установки MySQL для Excel Installer на вашем компьютере должно быть установлено следующее:
-
.NET Framework 4.0 (клиент или полный профиль).
-
Microsoft Office Excel 2007 или выше, для Microsoft Windows.
-
Visual Studio Tools для Office 4.0 и MySQL Installer могут установить это для вас.
-
Доступное соединение с MySQL Server.
MySQL для Excel загружается и выполняется путем выбора вкладки меню «Данные» в Excel, а затем выбора значка «База данных MySQL для Excel». Это открывает новую боковую панель Excel с доступными опциями MySQL для Excel. Панель навигации со значком MySQL для Excel показана на следующем снимке экрана:
Редактировать данные MySQL в Excel
MySQL для Excel позволяет загружать и редактировать данные MySQL непосредственно из Microsoft Excel, или же вы можете сделать это вручную, нажав «Принять изменения».
В приведенном ниже примере используется таблица расположения примера базы данных сотрудников, но экран будет выглядеть одинаково для любой таблицы. В MySQL для Excel откройте соединение MySQL, щелкните схему сотрудника, затем выберите таблицу местоположений, нажмите «Изменить данные MySQL», затем выберите «Импорт», чтобы импортировать данные в новый лист Microsoft Excel для редактирования.
Вот пошаговое руководство по редактированию и фиксации данных:
Шаг 1:
Загрузить Microsoft Office Excel 7
Шаг 2:
Нажмите на вкладку данных , см. Рисунок выше, значок базы данных «MySQL для Excel» появится ниже.
Шаг 3:
Нажмите на значок базы данных «MySQL для Excel». Он открывает новую боковую панель Excel с доступными параметрами MySQL для Excel. Панель навигации со значком MySQL для Excel показана на следующем рисунке.
Здесь наша База данных является сотрудником, и мы работаем с таблицей местоположений , но экран будет выглядеть одинаково для любой таблицы.
Шаг 4:
В боковой панели MySQL для Excel откройте соединение MySQL двойным щелчком мыши. Здесь наше соединение — Локальный экземпляр MySQL5.6, и для принятия пароля появится следующий экран.
Шаг 5:
Введите пароль для соединения с сервером MySQL. Базы данных будут отображаться в боковой панели MySQL для Excel. Наша База данных является сотрудником. Смотрите следующую картинку.
Шаг 6:
Дважды щелкните по нужной базе данных, и отобразятся таблицы в базе данных. Наш стол — это местоположение. Смотрите следующую картинку.
Шаг 7:
Выберите таблицу, которую вы хотите редактировать, нажмите «Редактировать данные MySQL» на панели навигации, как показано выше, и посмотрите следующий снимок экрана.
Шаг 8:
Нажмите кнопку «Импорт», как указано на картинке выше, и посмотрите следующий снимок экрана. Появятся данные выбранной таблицы, и если вы наведете курсор на диапазон данных, в противном случае появится кнопка «Восстановить данные и зафиксировать изменения» (указанная красным прямоугольником).
Шаг 9:
Здесь, в нашей таблице, идентификатор первого столбца является первичным ключом. Если мы изменим значение ID в ячейке A19 вместо 17 и нажмем клавишу ввода, цвет этой ячейки будет зеленым. Теперь мы изменили значение ячейки F16 Лондона и нажмите клавишу ввода, цвет ячейки изменится на зеленый, а желтый цвет в последнюю очередь означает, что ячейки принимают новые данные. Введенные здесь данные вставляются в таблицу MySQL.
Шаг 10:
Теперь, если мы нажмем кнопку «Восстановить данные», посмотрите следующий снимок экрана.
Здесь на картинке выше, если вы нажмете кнопку «Обновить данные из БД», данные будут обновлены и отобразятся исходные данные из БД, а если вы нажмете «Восстановить измененные данные», вы потеряете только что сделанные изменения. На этом этапе, если вы нажмете кнопку «Применить изменения», посмотрите следующий снимок экрана.
Здесь на рисунке выше вы видите сообщение об ошибке, и цвет ячейки A19 изменился с зеленого на красный, потому что столбец идентификатора является первичным ключом, а уникальность здесь нарушена. Теперь мы вернули значение ячейки A19 в исходное значение, то есть 18, и нажмите кнопку Commit Changes, и теперь посмотрим на снимок экрана ниже.
На изображении выше показано, как цвета ячейки F16 преобразованы из зеленого в синий, что означает успешное выполнение изменений. Теперь вы можете закрыть сохранение окна Excel или нет, но таблица базы данных была обновлена. Вы можете видеть это, чтобы сделать шаг снова. Если вы установили флажок «Автоматическая фиксация», эффект сразу же отобразится на вашем листе, и данные будут обновлены в базе данных MySQL.
Импорт данных MySQL в Excel
Данные можно импортировать из MySQL в электронную таблицу Microsoft Excel с помощью параметра «Импорт данных MySQL» после выбора таблицы, представления или процедуры для импорта.
Прежде всего, вы делаете первые 6 шагов, описанных выше в «Редактировании данных MySQL в Excel», затем выбираете таблицу, которую хотите импортировать. Здесь наш стол — местоположение. Поэтому выберите таблицу местоположений, а затем нажмите «Импорт данных MySQL» и посмотрите на скриншот, показанный ниже.
Выбор столбцов для импорта
По умолчанию все столбцы выбраны и будут импортированы. Определенные столбцы могут быть выделены (или не выбраны) с использованием стандартного метода Microsoft Windows: либо Control + щелчок мышью для выбора отдельных столбцов, либо Shift + щелчок мышью для выбора диапазона столбцов.
Белый цвет фона указывает, что столбец или столбцы были выбраны, и они готовы к импорту, с другой стороны, серый цвет указывает, что столбцы не выбраны и столбец не будет импортирован.
Если щелкнуть правой кнопкой мыши в любом месте сетки предварительного просмотра, откроется контекстное меню с параметром «Нет» или «Выбрать все» в зависимости от текущего состояния.
Таблица импорта
Включить имена столбцов в качестве заголовков: по умолчанию этот параметр включен, и он обрабатывает имена столбцов в верхней части электронной таблицы Microsoft Excel как строку «заголовков» и будет вставлен в качестве заголовка.
Ограничить и строки и начать с строки : по умолчанию этот параметр отключен, если включен, это ограничивает диапазон импортируемых данных. Параметр Limit to по умолчанию равен 1, и этот предел может быть изменен путем определения количества строк для импорта. Параметр «Начать со строки» по умолчанию равен 1, т. Е. Начинается с первой строки, и его можно изменить, определяя номер, с которого начинается импорт. Каждый параметр имеет максимальное значение COUNT (строки) в таблице.
Теперь предполагается, что мы хотим импортировать столбцы LOATION_ID и CITY. Щелкните мышью по столбцу LOCATION_ID, затем нажмите и удерживайте клавишу CTRL, щелкните столбец CITY и посмотрите следующий снимок экрана.
Теперь, если мы нажмем кнопку «Импорт», все строки для этих двух столбцов будут импортированы в Microsoft Excel Worksheet.
Предполагается, что мы хотим импортировать только 6 строк, начиная с 3-го ряда. Теперь посмотрите следующий снимок экрана.
Здесь на рисунке выше показано, что все столбцы выбраны, и значение Limit to равно 6, что означает, что будет импортировано 6 строк, и начало импорта начнется с 3-й строки, потому что мы установили значение Start with Строка 3. Теперь нажмите кнопку «Импорт» и посмотрите следующий снимок экрана.
Добавить данные Excel в MySQL
Данные электронной таблицы Microsoft Excel можно добавлять в таблицу базы данных MySQL с помощью параметра «Добавить данные Excel в таблицу».
Отображения столбцов
Сопоставление столбцов Excel со столбцами MySQL можно выполнить автоматически (по умолчанию), вручную или с помощью хранимой процедуры сопоставления. Чтобы добавить данные из Excel в MySQL, необходимо выполнить следующий шаг:
Сначала выполните 6 шагов «Редактирования данных MySQL в Excel», затем введите записи в таблицу Excel, совместимую со структурой таблицы MySQL, в которую вы хотите добавить записи. Вот пример, в котором мы взяли только одну строку, вы можете взять более одной строки и затем выбрать записи. Смотрите следующий снимок экрана.
Теперь нажмите «Добавить данные Excel в таблицу», как упомянуто выше, и посмотрите на экран как.
Здесь на картинке выше, вы ищете два цвета для легенды. Один красный, а другой зеленый.
Зеленый цвет указывает, что исходный столбец сопоставлен (сопоставленный означает, что исходные столбцы в приведенной выше сетке, созданной в электронной таблице, были сопоставлены со структурой таблицы MySQL в качестве целевых столбцов, показанных в нижней сетке) с целевым столбцом и здесь на рисунке выше. показывает, что все исходные столбцы были сопоставлены с целевыми столбцами.
Если вы перетащите заголовок любого целевого столбца на зеленый цвет и оставите его вне сетки, цвет целевого столбца будет красным, а цвет исходного столбца — серым. Смотрите на картинке ниже.
Здесь на рисунке выше целевой столбец 4 стал красным, а исходный столбец 4 — серым.
Красный цвет означает, что целевой столбец не сопоставлен, а серый цвет означает, что исходный столбец не сопоставлен.
Следует отметить, что исходный столбец может быть сопоставлен с несколькими целевыми столбцами, хотя это действие генерирует диалоговое окно с предупреждением, и при щелчке правой кнопкой мыши по целевому столбцу отображается меню с параметрами либо «Удалить сопоставление столбцов» для одного столбца, либо «Очистить». Все сопоставления для всех столбцов.
Предположим, мы отображаем вручную путем перетаскивания исходного столбца 4 с целевыми столбцами 4 и столбцами 5 Целевой столбец 4 будет отображаться просто, но при выполнении процесса для целевого столбца 5 появится диалоговое окно с предупреждением, показанное ниже.
Методы картирования
Вот посмотрите три метода отображения:
Метод автоматического сопоставления пытается сопоставить имена исходных столбцов Excel с именами столбцов целевой таблицы MySQL.
В методе сопоставления вручную имена столбцов источника перетаскиваются вручную с именами столбцов назначения. После выбора Автоматического метода также можно выполнить метод ручного перетаскивания.
Вы можете сохранить свои собственные стили сопоставления с помощью кнопки « Сохранить сопоставление» и сохранить имя, например «name (dbname.tablename)», и оно будет доступно в поле со списком «Метод сопоставления».
Сохраненные сопоставления могут быть удалены или переименованы в диалоговом окне « Дополнительные параметры ».
Расширенные настройки
Если мы нажмем кнопку «Дополнительные параметры», диалоговое окно будет выглядеть примерно так:
Выполните автоматическое сопоставление при открытии диалогового окна : с помощью этих параметров автоматически сопоставляется цель и источник при открытии диалогового окна «Добавить данные».
Автоматически сохранять сопоставление столбцов для данной таблицы . Чтобы проверить этот параметр, сохраняется каждая подпрограмма сопоставления после выполнения операции добавления. Процедура отображения сохраняется в формате «tablenameMapping (dbname.tablename)». Это может быть выполнено вручную с помощью кнопки Store Mapping.
Перезагрузите сохраненное сопоставление столбцов для выбранной таблицы автоматически : если существует сохраненная подпрограмма сопоставления, которая сопоставляет все имена столбцов в исходной сетке с целевой сеткой, то она автоматически загружается.
Расширенные параметры поля данных:
Используйте первые 100 (по умолчанию) строк данных Excel для предварительного просмотра и расчета типов данных. Это определяет количество строк, которые отображает предварительный просмотр, и значения, которые влияют на функцию автоматического сопоставления.
При проверке Использовать отформатированные значения данные из Excel обрабатываются как Текст, Двойной или Дата. Это включено по умолчанию. Если мы отключим его, существующие данные никогда не будут обрабатываться как тип даты, поэтому, например, это означает, что дата может быть представлена в виде числа.
Сохраненные сопоставления столбцов — это список сохраненных сопоставлений столбцов, которые были сохранены с помощью функции «Автоматически сохранять сопоставление столбцов для данной таблицы» или вручную с параметром «Сопоставление хранилищ».
После завершения всех шагов, если мы нажмем кнопку «Добавить», появится следующий экран.
Экспорт данных Excel в MySQL
Данные электронной таблицы Microsoft Excel можно экспортировать в новую таблицу базы данных MySQL с помощью параметра « Экспорт данных Excel в новую таблицу» . Сначала вы делаете первые 6 шагов, описанных выше, в разделе « Редактирование данных MySQL в Excel» . Затем введите несколько записей с нужным заголовком в электронную таблицу Excel и выберите записи. Теперь посмотрите пример записи на следующем рисунке —
Теперь нажмите «Экспорт данных Excel в новую таблицу» с помощью стрелки на изображении выше и посмотрите на следующий экран.
1 — Укажите уникальное имя для таблицы MySQL. Предположим, что имя таблицы MySQL «счет-фактура»
2 — Если установлен переключатель радиокнопки Добавить первичный ключ, будет добавлен дополнительный столбец первичного ключа, вы можете изменить имя столбца, и по умолчанию тип данных будет целым числом, которое отображается в 7.
3 — Когда вы установите переключатель «Использовать существующие столбцы», имена столбцов будут доступны в поле со списком, и вы сможете выбрать столбец первичного ключа из списка, и столбец будет выбран. Предположим, вы выбрали столбец INVOICE_NO, посмотрите следующую картинку.
Здесь на рисунке выше был выбран столбец INVOICE_NO, и теперь вы можете изменить имя столбца (точка 6), тип данных (точка 7) и ограничение (точка 9), которые активны.
4 — Если вы установите флажок Первая строка содержит имена столбцов (пункт 4), первый столбец в ваших данных Excel будет заголовком, в противном случае это будет столбец1, столбец2 и т. Д.
5 — Предположим, вы изменили тип данных и имя столбца для других столбцов, которые вы можете нажать на заголовок столбца. Предполагая, что мы хотим изменить тип данных INVOICE_DT, нажмите на INVOICE_DT, и этот столбец будет выбран, а затем вы можете использовать пункты 6,7 и 9.
6 — Вы можете изменить имя столбца.
7 — Вы можете изменить тип данных
8 — Расширенный параметр показывает следующее диалоговое окно.
Расширенные настройки
Используйте первые 100 (по умолчанию) строк данных Excel для предварительного просмотра и вычисления типов данных : этот параметр определяет количество строк, отображаемых при предварительном просмотре, и указанные значения влияют на функцию автоматического сопоставления.
Анализировать и пытаться определить правильный тип данных на основе содержимого поля столбца. Этот параметр пытается анализировать данные и определять тип данных для столбца. Когда столбец содержит несколько типов данных, он определяется как VARCHAR.
Добавить дополнительный буфер к длине VARCHAR (округлить до 12, 25, 45, 125, 255) : если он включен, он автоматически определяет тип данных и устанавливает значение VARCHAR, а затем находит максимальную длину для всех строк в столбце, и округляет максимальную длину до одной из указанных выше длин и, если она отключена, то длина VARCHAR устанавливается равной длине самой длинной записи в электронной таблице Excel.
Автоматически установите флажок «Индекс» для столбцов с целочисленными значениями : по умолчанию этот параметр включен, и тогда для столбцов с целочисленным типом данных будет включен параметр «Создать индекс» по умолчанию.
Автоматически установите флажок «Разрешить пустой» для столбцов без индекса: по умолчанию этот параметр включен, а при включении для столбцов без флажка «Создать индекс» автоматически включается параметр конфигурации «Разрешить пустой».
Использовать отформатированные значения: по умолчанию этот параметр включен, и данные из Excel обрабатываются как текстовые, двойные или даты, но если они отключены, они независимы, то есть не имеют определенного типа данных.
Удалить столбцы, которые не содержат данных, в противном случае пометьте их как «Исключенные»: если этот параметр включен, столбцы без данных в Excel удаляются и не отображаются на панели предварительного просмотра. По умолчанию этот параметр отключен, и тогда эти столбцы будут существовать, но с включенным параметром «Исключить столбец».
После завершения всех настроек нажмите кнопку «Экспортировать» и увидите следующий снимок экрана:
Предыдущий: MySQL DROP
Далее: Резервное копирование и восстановление MySQL
In this article, you will learn how to import a MySQL Table from the database into an Excel table using an ODBC Database Query. If you are looking to do the reverse and import an Excel table into any SQL database (including MySQL), try my other tutorial here. This tutorial should work on Microsoft Excel 2016 or greater with Microsoft Windows.
Step 1: Install MySQL Connector/ODBC
Firstly, you must install the MySQL Connector/ODBC software. This is the ODBC driver that will allow you to add a MySQL server as a data source. You can download the driver here: https://dev.mysql.com/downloads/connector/odbc/. It is important to match the architecture of the driver with the architecture of your Excel install. In my case, I have a 64-bit system but 32-bit Excel so I actually needed the 32-bit driver. You can check your Excel install by going to File > Account and clicking About Excel.
Step 2: Setup the MySQL Server as an ODBC Data Source
With MySQL Connector/ODBC installed, you need to configure the data source in Windows so we can use it in Excel. Open the ODBC Data Sources Administrator by searching for it in the start menu. If you are given the option of opening the 32-bit or 64-bit window, open the one that matches the driver you installed and your Excel install. In my case, this was the 32-bit manager. You should now see the driver listed under the Drivers tab.
You can add the new data source as either a System DSN or User DSN, with the former meaning it will be accessible to all users on the system and the latter being accessible only to the current user. To add as a User DSN, go to the User DSN tab and click Add…
Then, select the MySQL driver and click Finish to move the next step of adding the MySQL server details. Either the Unicode or ANSI driver should work, but if you require Unicode support ensure you use the Unicode variant.
Next, fill out the details for your server and test the connection. You may select a database at this stage if you wish, but you will have the opportunity to select it in Excel later if you leave the database field blank for the time being. Click OK to finalize the data source configuration and close the ODBC Data Source Administrator.
Step 3: Create the Excel Query
Open Excel and go to the Data tab. Click Get Data and choose From Other Sources > From ODBC.
Select the data source that you configured in the ODBC Data Source Administrator from the dropdown.
If asked for credentials, choose Default or Custom. You already configured the credentials when setting up the data source in Step 2.
Finally, click Connect to connect to the server. A list of tables will be loaded that you can choose to import into Excel. Select the table you want to import and click Load to load it in directly. If you need to modify the data, you can do so by clicking Transform Data. That will open the query editor allowing you to make changes that will be repeated each time the query refreshes. For more information on transforming data, please see the video tutorial at the top of this page.
With the query finished, you can make changes by clicking the table and clicking the Query tab to refresh or change query properties such as automatic refresh.
That’s it! Please comment below with any questions you may have and share the tutorial if you found it helpful.
Last update on August 19 2022 21:51:24 (UTC/GMT +8 hours)
Installing and Configuring
Import and export data between MySQL and Excel has become much easier in Excel 2007 than it’s previous versions. To explore the feature, you need to install MySQL For Excel.
You can install the MySQL For Excel component while installing MySQL Community Server 6. Or you may install it as an add-on upon your existing MySQL Server installation. Installation of this component has some prerequisites, though.
MySQL for Excel Requirements
You must have following installed on your machine for installing MySQL For Excel Installer :
-
.NET Framework 4.0 (Client or Full Profile).
-
Microsoft Office Excel 2007 or greater, for Microsoft Windows.
-
Visual Studio Tools for Office 4.0 and MySQL Installer may install this for you.
-
An available MySQL Server connection.
MySQL for Excel is loaded and executed by selecting the Data menu tab in Excel, and then choosing the «MySQL for Excel» Database icon. This opens a new Excel sidebar with the available MySQL for Excel options. The navigation bar with the MySQL for Excel icon is shown in the following screen shot:
Edit MySQL Data in Excel
MySQL for Excel enables you to load and edit MySQL data directly from Microsoft Excel, or yon can do it manually by pressing Commit Changes.
The example below uses the location table of the example employee database, but the screen will look the same for any table. Within MySQL for Excel, Open a MySQL Connection, click the employee schema, Next, select the location table, click Edit MySQL Data, then choose Import to import the data into a new Microsoft Excel worksheet for editing.
Here is the step by step guide to editing and commit the data:
Step 1:
Load Microsoft Office Excel 7
Step 2:
Click on Data Tab, see the above picture, the» MySQL for Excel» Database icon will appear shown below.
Step 3:
Click on «MySQL for Excel» Database icon. It opens a new Excel sidebar with the available MySQL for Excel options. The navigation bar with the MySQL for Excel icon is shown in the following picture.:
Here our Database is employee and we are working with location table, but the screen will look the same for any table.
Step 4:
Within MySQL for Excel sidebar open a MySQL connection by double clicking. Here our connection is Local instance MySQL5.6 and with the following screen will appear for accepting the password.
Step 5:
Enter password for connection with MySQL server. The databases will show in MySQL for Excel sidebar. Our Database is employee. See the following picture.
Step 6:
Double click on your desire database, and the tables within the database will display. Our table is location. See the following picture.
Step 7:
Select the table which you want to edit, click «Edit MySQL Data» inside the navigation bar as shown above, and see the following screen shot.
Step 8:
Click on Import button as mention in the above picture, and watch the following screen shot. The data of the selected table will appear and if you place the cursor on the data range the Revert Data and Commit Changes button ( specified by a red color rectangle ) will appear otherwise not.
Step 9:
Here at our table, the first column ID is a primary key. If we change the value of ID in A19 cell 17 instead of 18 and press enter key the color of this cell will be green. Now we have changed the value of F16 cell is London and press enter key the cell color will change into green, and the color yellow at the last, indicate that the cells that accept new data. Data entered here is inserted into the MySQL table.
Step 10:
Now if we click the Revert Data button, watch the following screen shot.
Here in above picture if you click the Refresh Data from DB the data will be refresh and display the original data from DB, and if you click on Revert Changed Data, you will loose your changes just made. In this stage, if you click on Commit Changes button look the following screen shot.
Here in the above picture, you are looking an error message, and the color of A19 cell changed from green to red, that is because the ID column is the primary key and the uniqueness have been violated here. Now we returned the value of A19 cell in its original value, i.e. 18, and click on Commit Changes button, and now look the below screen shot.
In the above picture shows the color of cell F16 have converted from green to blue, that means Commit Changes done successfully. Now you can close the Excel window saving or not but the database table has been updated. You can see it to do the step again. If you checked the Auto Commit check box, the effect immediately is seen in your sheet and data will be updated in MySQL database.
Import MySQL Data into Excel
Data can be imported from MySQL into a Microsoft Excel spreadsheet by using the Import MySQL Data option after selecting either a table, view, or procedure to import.
First of all, you do the first 6 steps describe above in «Edit MySQL Data in Excel» then select your table which you want to import. Here our table is location. So select the location table and then click «Import MySQL Data» and look the appeared screen shot here in the below.
Choosing columns to import
By default, all columns are selected and will be imported. Specific columns may be selected (or unselected) using the standard Microsoft Windows method of either Control + Mouse click to select the individual columns, or Shift + Mouse click to select a range of columns.
The background color white indicates, the column or columns have been selected and they are ready to be imported, on the other hand, the gray color indicates that the columns are not selected and the column will not be imported.
Right-clicking anywhere in the preview grid opens a context-menu with either a Select None or Select All option, depending on the current status.
Importing Table
Include Column Names as Headers: By default, this option is enabled, and this treats the column names at the top of the Microsoft Excel spreadsheet as a «headers» row and will be inserted as a header.
Limit to and Rows and Start with Row : By default, this option is disabled if enabled, this limits the range of imported data. The Limit to option defaults to 1 and this limit can be changed by defines the number of rows to import. The Start with Row option defaults to 1, i.e. starting from the first row, and it can be changed by defines the number from where the import begins. Each option has a maximum value of COUNT(rows) in the table.
Now assumed that we want to import the columns LOATION_ID and CITY. Click the mouse on LOCATION_ID column and then press and hold CTRL key and click on CITY column, and look the following screen shot.
Now if we click the Import button all the rows for this two columns will be imported in Microsoft Excel Worksheet.
Assumes that, we want to import only 6 rows beginning from the 3rd row. Now look the following screen shot.
Here in the above picture shows all the columns have selected and the value of Limit to is 6, that means a number of 6 rows will be imported and the beginning of importing will start from the 3rd row because we have set the value of Start with Row is 3. Now click the Import button and look the following screen shot.
Append Excel Data into MySQL
The Microsoft Excel spreadsheet data can be appended to a MySQL database table by using the Append Excel Data to Table option.
Column mappings
Mapping the Excel columns to the MySQL columns can be executed automatically (default), manually, or by using a stored mapping routine. To append the data from Excel toMySQL the following step to be followed:
At first do th e above 6 steps of «Edit MySQL Data in Excel» then input records in excel spreadsheet compatible to the structure of MySQL table in which you want to append the records. Here is the example in which we have taken only one row, you may take more than one rows and then select the records. See the following screen shot.
Now click on the Append Excel Data to Table as mention above, and look the screen like.
Here in the above picture, you are looking two colors for the legend. One is Red and another is Green.
The Green color indicate that a source column is mapped ( mapped means the source columns in above grid created in the spreadsheet have been matched with structure of the MySQL table as target columns shown in below grid ) to a target column and here in the above picture shows all the source columns have been mapped with target columns.
If you drag any target column heading backed by green color and leave it in outside the grid, the color of the target column will be Red and the color of the source column will be Gray. See in below picture.
Here in the above picture, the target column4 became Red and source column4 became Gray.
The Red color indicates that a target column is not mapped and the Gray color indicate that, a source column is not mapped.
It is to be noted that, a source column may be mapped to multiple target columns, although this action generates a warning dialog and right-clicking on a target column shows a menu with options to either Remove Column Mapping for a single column or to Clear All Mappings for all columns.
Suppose, we are mapping manually by dragging source column4 with target column4 and column5. The target column4 will be mapping simply but when doing the process for target column5 the warning dialog will appear, show below.
Mapping methods
Here look the three mapping methods:
The automatic mapping method attempts to match the Excel source column names with the MySQL target table column names.
In the manual mapping method, source column names are manually dragged with the target column names. After the Automatic method is selected the Manual dragging method can also be performed.
You may store your own mapping styles using the Store Mapping button and saved a name like «name (dbname.tablename)» and it will be available in the Mapping Method combo box.
Stored mappings may be deleted or renamed within the Advanced Options dialog.
Advanced Options
If we click the Advanced Options button the dialog looks similar to:
Perform an automatic mapping when the dialog opens: By this options, it happens automatically to map the target and source when the Append Data dialog is opened.
Automatically store the column mapping for the given table:To check this option, stores each mapping routine after executing the Append operation. The mapping routine is saved using the «tablenameMapping (dbname.tablename)» format. It can be performed manually by using the Store Mapping button.
Reload stored column mapping for the selected table automatically: If a stored mapping routine exists which matches all column names in the source grid with the target grid, then it is automatically be loaded.
The advanced Field Data Options:
Use the first 100 (default) Excel data rows to preview and calculate data types. This determines the number of rows that the preview displays, and the values that affect the automatic mapping feature.
When you check the Use formatted values, the data from Excel is treated as Text, Double, or Date. This is enabled by default. If we make it disabled, the existing data is never treated as a Date type, so for example, this means that a date may be represented as a number.
The Stored Column Mappings is a list of saved column mappings that were saved with the «Automatically store the column mapping for the given table» feature, or manually with the Store Mapping option.
After completion all the steps if we click Append button the following screen will appear.
Export Excel Data into MySQL
Microsoft Excel spreadsheet’s data can be exported to a new MySQL database table by using the Export Excel Data to New Table option. At first, you do the first 6 steps above describe in Edit MySQL Data in Excel . Then enter some records with heading as you wish, into your Excel spreadsheet and select the records. Now look the sample records in the following picture —
Now click on Export Excel Data to New Table mention by the arrow in the above picture and look the following screen.
1 — Specify a unique name for the MySQL table. Suppose the name of the MySQL table is «invoice»
2 — If Add a Primary Key column radio button is checked an additional primary key column will be add, you can change the name of the column and by default, the data type will be an integer which is displaying in 7.
3 — When you check the Use Existing Columns radio button the column names will the available in the combo box and you can choose the primary key column from the list, and the column will be selected. Suppose you selected INVOICE_NO column, look the following picture.
Here in the above picture, the INVOICE_NO column has been selected and now you can change the Column Name (point 6), Data type (point 7) and the constraint (point 9) which are active.
4 — If you check the check box First Row Contains Column Names (point 4) the first column in your excel data will be heading otherwise it will be column1,column2,… etc
5 — Suppose you change the Data type and column name for other columns you can click on the column heading. Assumed that we want to change the Data type of INVOICE_DT, click on INVOICE_DT, and this column will be selected and then you can use point 6,7 and 9.
6 — You can change the Column Name.
7 — You can change the Data type
8 — Advance Option shows the following dialog.
Advanced Options
Use the first 100 (default) Excel data rows to preview and calculate data types: This option determines the number of rows that the preview displays and the specified values affect the feature of automatic mapping.
Analyze and try to detect correct data type based on column field contents: This option try to analyze the data and determine the data type for the column. When the column contains multiple types of data then it defined as VARCHAR.
Add additional buffer to VARCHAR length (round up to 12, 25, 45, 125, 255): When it is enabled, it detects the data type automatically and set to VARCHAR, then it find the maximum length for all rows within the column, and rounds it up the maximum length to one of the defined lengths above and when disabled, then the VARCHAR length is set to the length of the longest entry in the Excel spreadsheet.
Automatically check the Index checkbox for Integer columns: By default, this option is enabled , and then columns with an Integer data type will have the Create Index option enabled by default.
Automatically check the Allow Empty checkbox for columns without an index: By default, this option is enabled, and when enabled the columns without the Create Index checkbox checked will automatically enable the Allow Empty configuration option.
Use formatted values: By default, this option is enabled, and the data from Excel is treated as Text, Double, or Date but when disabled the data’s are independent, that is they have no specific data type.
Remove columns that contain no data, otherwise flag them as «Excluded»: When this option is enabled, columns without data in Excel are removed and not shown in the preview panel. By default, this option is disabled and then these columns will exist but have the Exclude Column option checked.
After completion, all setting click Export button the and see the following screen shot —
Previous:
MySQL DROP
Next:
MySQL backup and restore
На работе встретился с такой задачей «Надо сделать отчет, который брал бы данные из MySQL и закидывал его в таблицу Excel».
Ну вот я сейчас и опишу процесс конекта.
Есть:
1. Сервер MySQL
2. База данных на MySQL
3. Microsoft Excel 2010
Начнем:
1. Самое первое что нужно сделать, это установить MySQL Connector, актуальную версию можно скачать здесь
2. Нужно создать источник данных, идем вот сюда Панель управления — Администрирование — Источники данных (ODBC)
2.1. Вкладка Пользовательский DSN — Добавить — MySQL ODBC 5.1 Driver (должен появиться после манипуляций с п.1)
2.2. Откроется окно настройки источника, там в поле Data Source Name нужно написать имя сервера MySQL, порт оставляем стандартным (если вы при установке сервера не указали иной), User — имя пользователя, скорее всего root, Password — пароль, Database — тут можно указать базу, к которой подключаться, если все правильно на начальных этапах, то в выпадающем списке уже появятся существующие БД на сервере.
2.3. Ок. Источник данных создан.
3. Теперь необходимо создать строку подключения.
3.1. В любом месте компьютера создайте текстовый файл и переименуйте его в тип файла .udl
3.2. В открывшемся окне Использовать источник данных — выбрать ранее созданный источник данных (п. 2), ввести Пользователь и Пароль, жмем Ок.
3.3. Теперь созданный файл надо открыть с помощью Блокнот’а и там будет что-то подобное:
[oledb]
; Everything after this line is an OLE DB initstring
Provider=MSDASQL.1;Persist Security Info=False;User ID=root;Data Source=MySQL
то, что начинается с Provider и до MySQL и есть строка подключения, т.е. Provider=MSDASQL.1;Persist Security Info=False;User ID=root;Data Source=MySQL
она нам понадобиться при настройке Excel.
4. Теперь скачиваем специально подготовленный мной документ Excel
5. Открываем, возможно будет ругаться из-за того, что у вас сервер отличный от моего.
6. Идем на вкладку Данные — Параметры — Источник данных — Свойства подключения — Вкладка Определения.
6.1. Вводим Строка подключения, которая у нас появилась ранее (п. 3.3.), вводим текст SQL команды и жмем Ок.
Все, если все правильно было сделано, то в правой части должны появиться поля, которые вы хотели выбрать. Советую на сервере протестировать синтаксис и правильность своего SQL запроса, чтобы не появлялись дополнительные вопросы. Лично я работаю с MySQL через HeidiSQL, там сделал запрос, а потом просто скопировал его в Excel.
In daily database maintenance, import and export operations are often needed for database backup, analysis, and migration. In this tutorial, we will explain in detail all the common methods of importing and exporting data in MySQL and MariaDB (note: MySQL and MariaDB two database operation commands are the same, interchangeable.
This tutorial will cover this in detail
MySQL/MariaDB MySQL/MariaDB
SQL dump dump dump dump dump dump dump dump dump dump
(2) The database in the remote server of Ali Cloud/Tencent Cloud is directly exported to the local computer
(3) Run the into outfile command to export data to CSV/Excel
Tip: If you are looking for a data migration solution, please check out another tutorial I wrote specifically for MySQL data migration, including Tencent Cloud, Ali Cloud migration actual combat.
MySQL/MariaDB MySQL/MariaDB
(1) Import SQL files into MySQL/MariaDB database
(2) Use source to import database SQL files
(3) Import CSV/Excel files into the MySQL/MariaDB database
3. Use Kara Cloud to import and export MySQL/MariaDB data
How to use Cara cloud, 5 minutes to build a set of one-click import and export database system to adapt to their workflow. Carla cloud does not need to be deployed. It is plug and play and can be flexibly deployed according to requirements. It is suitable for back-end engineers to quickly build internal systems of enterprises, data product managers to view and analyze data, and data analysts to quickly build data sharing platforms to share with students in the group. Click here for details.
4. Prerequisites
Follow this tutorial to learn how to import and export MySQL or MariaDB databases
- A Linux server. This article uses Ubuntu as an example
- MySQL or MariaDB Server has been installed.
- MySQL or MariaDB Server has a database (for export)
- This tutorial uses MacOS to demonstrate local computer operations for both Windows and Linux
Export the MySQL or MariaDB database
1. How to use itmysqldump
Export data
The mysqldump command is the most frequently used tool for database export. It backs up the data in the database into a *.sql ended text file where the table structure and data are stored.
The mysqldump command is also simple. It first queries the TABLE structure that needs to be backed up, then generates a CREATE TABLE ‘TABLE’ statement, and finally converts all the records in the TABLE into an INSERT statement.
You can think of it as a batch export import script. When importing data, import data according to standard statements, greatly reducing the occurrence of strange unknown errors.
Mysqldump
$ mysqldump -u username -p database_name data-dump.sql
Copy the code
username
Is the login name of the databasedatabase_name
Is the name of the database to be exporteddata-dump.sql
Is a file in the output directory of files
Export actual combat — Export data from MySQL database in Ali Cloud server
$ mysqldump -u kalacloud -p kalacloud_database /tmp/kalacloud-data-export.sql
Copy the code
kalacloud
: Database accountkalacloud_database
: database name/tmp/kalacloud-data-export.sql
: Indicates the directory for exporting files from the database
Enter the password of the database kalacloud account to execute the command. If there is no error during the execution, the command line will not output anything.
We can CD to the TMP directory to view the result. As you can see, the kalacloud-data-export.sql export file has been generated in the TMP directory.
We are using head -n 5 kalacloud-data-export. SQL to check. You should see something like the image below.
Now that we have exported the specified database to a *.sql file, we’ll explain how to import this data into the database.
Further tip: We can use the SCP command to download the exported file to the local computer.
From the command line terminal of the local computer, type:
SCP [email protected]: / TMP/kalacloud - data - export. SQL/Users/kalacloud/DownloadsCopy the code
Root Account for logging in to the remote computer
192.168.180.134 is the IP address of the remote computer
/ TMP /kalacloud-data-export. SQL indicates the location on the remote computer where the database files to be downloaded to the local computer are stored
/ Users/kalacloud/Downloads for the local computer, location of the remote file to download to this directory
Use SCP to download the exported SQL file to the local PC for subsequent processing. Of course, we can also export to the local computer in one step, let’s continue to explain the advanced export method.
How to connect to MySQL database remotely
2. Advanced: Export the database from the remote server of Ali Cloud/Tencent Cloud to the local computer
Earlier we talked about how to operate the export database on a remote server and save the export to a remote server. Sometimes we need to export data to a product or operation for data analysis, or we are using a standalone MySQL database as a cloud service. In this case, you need to export data directly to a local computer.
$ mysqldump -h remote_IP_address -u username -p -P3306 --default-character-set=utf8 --set-gtid-purged=OFF database_name /Users/kalacloud/Desktop/data-dump.sql
Copy the code
remote_IP_address
: IP address of the remote serverusername
: indicates the MySQL account that has the remote login permission3306
: Database port for remote login. The default value is 3306default-character-set=utf8
: Specifies the character set when exportingset-gtid-purged=OFF
: Global transaction ID (GTID) to enhance database master/standby consistency, fault recovery, and fault tolerance. When enabling this function, errors may occur. Therefore, disable this function.database_name
: Indicates the name of the database to be exported/Users/kalacloud/Desktop/data-dump.sql
: Specifies the path and file name for saving the file on the local PC
Mysqldump: mysqldump: Couldn’t execute ‘SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM, ‘$.»number-of-buckets-specified»‘)
You can add column-statistics=0 to the command. Because the earlier version of the MySQL database information_SCHEMA did not have a data table named COLUMN_STATISTICS, the new mysqldump is enabled by default, we can use this command to disable it.
Export actual combat — the ali cloud server in the database directly exported to the local computer
$mysqldump-h123.57.56.228 -ukalacloud-remote p-p3306 --default-character-set=utf8 --set-gtid-purged=OFF --column-statistics=0 kalacloud_database /Users/kalacloud/Desktop/kalacloud-data-export.sqlCopy the code
123.57.56.228
: INDICATES the IP address of the remote databasekalacloud-remote
: Database account that has the remote access permission.-P 3306
: Database access port, which can be modified based on site requirements./Users/kalacloud/Desktop/kalacloud-data-export.sql
: Specifies the path and file name for saving the file on the local PC
After the command is executed, there is no output from the command line, but you can see the exported file on the desktop.
You have exported the data to the remote database on the local desktop
Mysqldump can also be backed up into tables
Database database [database_one] database_one. SQL database database [database [database_one] databases [database [database_one] -uroot -p --single-transaction [database_one] [table_one] [table_two] database_table12.sql # mysqldump -uroot -p --single-transaction [database_one] [table_one] [table_two] database_table12.sql # mysqldump -uroot -p [database_one] --ignore-table=[database_one.table_one] --ignore-table=[database_one.table_two] database_one.sql # Mysqldump -uroot -p [database_one] --no-data [database_one.defs]. SQL # mysqldump -uroot -p [database_one] --no-create-info [database_one.data].sqlCopy the code
For the problem of database migration between two servers, please see my «How to migrate MySQL Database, Aliyun, Tencent Cloud Migration Case».
Use 3.into outfile
Export MySQL/MariaDB data to CSV/Excel
When you need to export data to operations or products for data analysis, exporting CSV files is more convenient.
mysql select * from users into outfile '/var/lib/mysql-files/users.csv' FIELDS TERMINATED BY ',';
Copy the code
FIELDS TERMINATED BY ‘,’ data is separated BY,.
First, log in to MySQL shell and select the database to export: use kalacloud_database; Then execute the export command.
After the CSV file is exported, a success message is displayed. If you go to the export directory, the CSV file is exported.
Error: Into outfile
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
Copy the code
This is because your MySQL configuration —secure-file-priv limits where the exported files can be stored.
You can use the following command to view the specific configuration information
show global variables like '%secure_file_priv%';
Copy the code
If secure_FILe_priv is NULL, import or export is not allowed. If secure_file_priv is the path (/var/lib/mysql-files/), only the path directory can be executed. If secure_FILe_priv has no value, it can be imported or exported in any directory.
You can open my.cnf or my.ini, add the following statement, and restart MySQL Server
secure_file_priv=''
Copy the code
Save a query to a file. Save a query to a file in MySQL.
MySQL or MariaDB database import data
Next we’ll show you how to import *.sql into the database. Let’s start with a new database for demonstration purposes.
MySQL select * from ‘root’;
$ mysql -u root -p
Copy the code
Enter the login password to enter the MySQL shell state. Next we create a new database, in this case kalacloud_new_DATABASE as the new database name.
Mysql CREATE DATABASE kalacloud_new_database;Copy the code
After the command is executed, the content is returned
Query OK, 1 row affected (0.00 sec)
Copy the code
With the new database created for the demo, we exit the MySQL shell with CTRL+D
1. Direct usemysql
Importing SQL files
/ TMP /kalacloud-data-export. SQL/TMP /kalacloud-data-export. SQL
mysql -u root -p kalacloud_new_database /tmp/kalacloud-data-export.sql
Copy the code
root
: User name that you can log in to the database.kalacloud_new_database
: The newly created empty database into which this command imports data./tmp/kalacloud-data-export.sql
This is the SQL file that we exported from the database above. Here we import it into the new database.
If the command is successfully executed, no message is displayed. If the command fails to run, the failure cause is displayed. To check whether the import was successful, we can log in to MySQL to view and examine the data in the database.
Log in to MySQL Server and run the USE kalacloud_new_database command. Select the new database where we just imported the data and use SHOW TABLES; SELECT * FROM users; SELECT * FROM users; Open the table to view the contents.
Parsing the MySQL configuration file line by line
2. Usesource
Import the MySQL/MariaDB DATABASE SQL file
/ TMP /kalacloud-data-export. SQL/TMP /kalacloud-data-export. SQL
mysql USE kalacloud_new_database;
Copy the code
First select the database kalacloud_new_database that you want to import and return the result.
Database changed
Copy the code
And then use source
mysql source /tmp/kalacloud_new_database.sql;
Copy the code
After executing the source command, MySQL starts the import, and then we use SHOW TABLES and select to check whether the SQL file is imported properly.
As you can see in the figure above, the data has been imported successfully.
Note: the difference between source and mysql
- Commands are executed in different environments:
source
Execute in MySQL sell,mysql
On the terminal command line - Returns different results:
source
Each row will be returned consecutively. If the volume is large, the speed may be affected.mysql
Return the result when all is done. - Whether to stop execution:
source
Execution will not be terminated if an error is reported.mysql
Execution will be terminated if an error is reported.
MySQL triggers 6 kinds of situations
3. Import the CSV file to the MySQL or MariaDB database
In addition to importing SQL class files directly, we sometimes encounter the need to import CSV files. The steps to import a CSV file are very different from those to import SQL directly, so let’s explain how to import a CSV file.
Let’s start with MySQL Shell:
$ mysql -uroot -p
Copy the code
Create a new empty database:
mysql CREATE DATABASE kalacloud_new_database;
Copy the code
Unlike *. SQL, you need to CREATE tables before importing a CSV file. You need to use CREATE TABLE to CREATE tables based on the columns contained in the CSV file.
CREATE TABLE `users` (
`id` VARCHAR(255) NULL,
`name` VARCHAR(255) NULL,
`phone` VARCHAR(255) NULL,
`states` VARCHAR(255) NULL,
`file_size` VARCHAR(255) NULL,
`sale` VARCHAR(255) NULL,
`copyright` VARCHAR(255) NULL,
`homepage` VARCHAR(255),
`complaint` VARCHAR(255) NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy the code
It is recommended that all fields accept NULL values and do not set primary keys for the time being. Because we don’t know if the data in the CSV file we are about to import is complete or regular.
It is recommended to use the VARCHAR field first, even for numbers, to prevent strange errors caused by improperly formatted data in files.
We can verify, clean and modify the database after data import.
/var/lib/mysql-files/users.csv; /var/lib/mysql-files/users.csv; Let’s use the LOAD DATA INFILE SQL statement to import the CSV file into the newly created table.
load data infile '/var/lib/mysql-files/users.csv'
into table users
FIELDS TERMINATED BY ','
ENCLOSED BY '"';
Copy the code
Fields are separated by commas and strings are enclosed in double quotes. If the first line of your CSV is a header rather than data, you can also add IGNORE 1 ROWS; When importing, ignore the first line.
After the import is successful, run the select * from users command. Check whether the data in the preliminary table is correct.
Extended reading: You can also use Workbench, the free MySQL graphical management tool, to do this. For more information, see my MySQL Workbench Chinese Guide.
3. Use «Cara Cloud» to import and export data with one click
In addition to terminal command operations such as MySQL/MariaDB data migration, most MySQL/MariaDB data import and export operations are for data display, analysis, collaborative sharing and other application scenarios at the product and operation levels.
For example, when back-end engineers receive product requirements and assist in exporting certain data, if such requirements occur frequently, it is recommended to use Kara Cloud. Kara Cloud is a new generation of low-code development tools that do not require installation and deployment and can access common databases and apis including MySQL with one click.
Not only can be as flexible as the command line, but also according to their own workflow, customized development. No tedious front-end development, just simple drag and drop, can quickly build enterprise internal tools. Months of development work can be reduced to a few days after using Kala cloud. Welcome to try our Kala cloud.
Cara Cloud provides quick access to common databases and apis
Kara Cloud can easily build data kanban according to the workflow requirements of the company, and can share data with partners in the group
A single line of code can map data to a specified component by dragging and dropping the front-end code.
Cara cloud can directly add export button, export data format suitable for all kinds of analysis software, convenient and fast. Open the Cara Cloud now, import and export your data
4. To summarize
In this tutorial, we explained how to import and export databases to SQL files and CSV files. There are many other changes to mysqldump. You can refer to the mysqlDump documentation for more information. More database-related tutorials can be found at Cara Cloud.