Oracle sql developer import from excel

Задача. У вас есть файл Excel – и вы хотите, чтобы эти данные были помещены в таблицу. Я покажу вам, как это делается, и мы задокументируем каждый шаг с большим количеством иллюстраций.

Прочитав этот пост, вы будете готовы с уверенностью импортировать данные в существующую таблицу из Excel. Хотите создать новую таблицу из Excel? Мы тоже можем это сделать.

В нашем примере я буду использовать таблицу HR.EMPLOYEES для создания XLS-файла для нашего импорта. Мы будем использовать этот файл Excel для заполнения пустой копии таблицы EMPLOYEES в другой схеме.

Шаг 0: Пустая таблица Oracle и ваш файл Excel

У вас есть таблица Oracle и один или несколько файлов Excel.

Шаг 1: Выбираем «Импорт данных» по правому щелчку мыши

Шаг 2: Выберите свой входной файл (XLSX) и проверьте данные

Если вы уже запускали этот мастер раньше, вы можете выбрать файлы из предыдущих сеансов.

Когда вы выберете файл, мы захватим первые 100 строк для просмотра ниже. Этот «Предел строк предварительного просмотра» определяет, сколько строк вы можете использовать для проверки ИМПОРТА по мере прохождения мастера. Вы можете увеличить его, но это потребует больше ресурсов, так что не сходите с ума.

Кроме того, есть ли в вашем файле Excel заголовки столбцов? Хотим ли мы рассматривать их как строку к таблице? Скорее всего, нет. Если вы снимите флажок «Заголовок», имена столбцов станут новой строкой в вашей таблице – и, вероятно, не будут вставлены.

Иногда ваш файл Excel имеет несколько заголовков, или вам может потребоваться импортировать только определенное подмножество электронной таблицы. Используйте опцию «Пропустить строки», чтобы получить правильные данные.

Шаг 3: Создайте сценарий или импортируйте автоматически

По мере прохождения шагов в мастере мы будем держать панель предварительного просмотра содержимого файла под рукой, так что вам не придется нажимать  alt+tab туда и обратно от Excel до SQL Developer.

Для этого упражнения будет использоваться метод «Вставки» (Insert). Каждая строка, обработанная в файле Excel, приведет к выполнению инструкции INSERT в таблице, в которую мы импортируем.

Если вы выберете «Вставить скрипт», мастер завершит работу скриптом ВСТАВКИ на вашем листе SQL. Это хорошая альтернатива, если вы хотите настроить SQL, или если вам нужно отладить/посмотреть, почему метод «Insert» не работает.

Шаг 4: Выберите столбцы Excel для импорта

Мастер по умолчанию использует все используемые столбцы Excel в том порядке, в котором они находятся в файле.

У вас может быть файл Excel со 100 столбцами, но ваша таблица имеет только 30. Здесь вы даете команду SQL Developer, какие столбцы должны использоваться для импорта. Вы также можете изменить порядок столбцов, что может сделать следующий шаг немного проще.

Шаг 5: Сопоставьте столбцы Excel со столбцами таблицы

Левая панель представляет столбцы в файле XLS. Информация справа показывает, куда идут эти данные и как они будут обрабатываться в Oracle.

Если вы не обращаете внимания и просто позволяете Мастеру импорта делать всё по умолчанию, то сейчас самое время проснуться. Есть большая вероятность, что порядок столбцов файла Excel не будет соответствовать определению вашей таблицы. На этом шаге вы указываете SQL Developer-у, какие столбцы в электронной таблице совпадают с какими столбцами в таблице Oracle.

А помните, как мы установили это окно предварительного просмотра на 100 строк? Мы внимательно изучаем данные, ищем проблемы, пытаясь вписать их в столбец вашей таблицы. Если мы обнаружим проблему, мы пометим столбцы этими «предупреждающими» символами.

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

Давайте на секунду поговорим о форматах даты и времени.

О TIMESTAMP тоже. В файле Excel у вас, вероятно, будут некоторые поля даты и времени, которые вы хотите переместить в столбцы формата  DATE или TIMESTAMP. SQL Developer обрабатывает эти значения как строки – и ВАМ нужно сообщить SQL Developer формат DATE или TIMESTAMP, чтобы иметь возможность их преобразовать.

Давайте посмотрим на HIREDATE.

Это значение «ха – ха» никогда не войдет в качестве значения HIRE_DATE – если только вы не храните ДАТЫ в VARCHAR2, — и если вы делаете это, то делаете это НЕПРАВИЛЬНО. Всегда храните ДАТЫ в формате DATE!

Видите выпадающий селектор «Формат» (Format)? SQL Developer по умолчанию установил строку формата ДАТЫ в ‘DD-MON-RR’ – мы пытаемся угадать это на основе строк, которые мы рассматриваем в этом окне предварительного просмотра 100.

Если мы ошиблись в догадках или не смогли разобраться, вам нужно будет ввести это самостоятельно. Документы Oracle могут помочь вам определить правильную модель формата ДАТЫ. Если вы видите небольшое предупреждающее изображение рядом со значениями даты на панели данных, возможно, у вас неправильный формат.

Шаг 6: Проверьте свои настройки и ВПЕРЕД!

Кнопка «Готово» запустит магию.

Нажмите на кнопку «Готово» (Finish).

Если Мастер столкнется с какими-либо проблемами при выполнении вставок, вы увидите следующее:

Помните те забавные данные, которые я поместил в файл Excel? Теперь это создает проблемы.

Я собираюсь сказать «Да», чтобы игнорировать все ошибки. Но если вам нужна КАЖДАЯ отдельная строка – вам нужно сказать «Отмена», чтобы начать все сначала. Затем вы можете либо исправить свои данные в файле Excel, либо внести изменения в свою таблицу, чтобы данные соответствовали/работали.

Нажав ‘Да», мы доберемся до конца нашей истории и наших данных!

Шаг 7: Посмотрите, Что сработало, а Что нет

Во-первых, есть ли плохие новости?

Если были строки, отклоненные базой данных, мы увидим их сейчас.

За этим диалогом находятся инструкции INSERT, которые мы пытались запустить, но не сработали. Вы можете изменить их вручную, чтобы исправить несколько записей. Но если у вас тысячи забракованных строк – лучше разобраться в файле (в источнике импорта).

Теперь давайте посмотрим на наши новые табличные данные!

Я люблю сладкий запах данных по утрам!

Обратите внимание на панель «Журнал» (Log). Там можно увиеть файл, с которым мы работали, и сколько времени потребовалось для загрузки данных.

Всё! Можно выдохнуть свободно. Импорт из файла Excel в таблицу базы данных Oracle завершен. В шапке статьи вы можете посмотреть видео инструкцию  — копию этого мануала на английском языке.

Вас заинтересует / Intresting for you:

I have installed SQL Developer in my system, but how can i utilize the GUI.
I am new to this and i want to import datas from Excel to Oracle database using SQL Developer

Thanks in advance

abatishchev's user avatar

abatishchev

97.3k85 gold badges297 silver badges432 bronze badges

asked Aug 10, 2010 at 2:04

user410565's user avatar

1

At what point did you get stuck?

A fast track:

  1. Create a connection to the database in SQL Developer
  2. Create a table as a destination for the xls data
  3. save excel data as csv
  4. right click on the table from step 2
  5. select ‘import data’
  6. select csv file
  7. use the wizzard

and bob is your uncle

Folowing methed creates the table for you

  1. Create a connection to the database in SQL Developer
  2. right click on tables folder
  3. Choose Import data
  4. select xls
  5. use the wizzard (provide table name, row limit, select columns, datatype per column)
  6. Finish

answered Aug 10, 2010 at 10:49

Rob van Laarhoven's user avatar

Содержание

  1. How to Import from Excel to Oracle with SQL Developer
  2. Step 0: The Empty Oracle Table and your Excel File
  3. Step 1: Mouse-right click – Import Data
  4. Step 2: Select your input (XLSX) file and verify the data
  5. Step 3: Create a script or import automatically
  6. Step 4: Select the Excel Columns to be Imported
  7. Step 5: Map the Excel Columns to the Table Columns
  8. Step 6: Verify your settings and GO!
  9. Step 7: See What Worked and What Didn’t
  10. Just a few more pointers when it comes to Excel
  11. The Movie
  12. How to insert data directly from Excel to Oracle Database
  13. 5 Answers 5
  14. 10 Exporting and Importing Metadata and Data
  15. Using SQL Developer for Exporting and Importing
  16. Example: Exporting Metadata and Data for a Table
  17. Example: Importing Metadata and Data Using a Script File
  18. Example: Exporting Data to a Microsoft Excel File
  19. Example: Importing Data from a Microsoft Excel File
  20. Using Other Tools for Exporting and Importing Data
  21. Choosing the Right Export/Import Utility
  22. Loading Data with SQL*Loader
  23. Methods SQL*Loader Uses to Load Data
  24. SQL*Loader Features
  25. Example: Using SQL*Loader
  26. Exporting and Importing Data
  27. Exporting and Importing with Data Pump Export and Data Pump Import
  28. Exportin g and Importing Data with the Export and Import Utilities

How to Import from Excel to Oracle with SQL Developer

THIS is your number one question – and it has been here on my blog since the day I posted it.

You have an Excel file – and you want that data put into a table. I’ll show you how, and we’ll document each step of the way with plenty of pictures.

You will be prepared to import data to an existing table from Excel with confidence after reading this post. Want to build a new table from Excel? We can do that, too.

Warning: This post has a LOT of pictures.

For our example I’ll be using the HR.EMPLOYEES table to create the XLS file for our import. We’ll use that Excel file to populate an empty copy of the EMPLOYEES table in another schema.

Step 0: The Empty Oracle Table and your Excel File

You have an Oracle table and you have one or more Excel files.

Step 1: Mouse-right click – Import Data

Step 2: Select your input (XLSX) file and verify the data

As you select the file, we’ll grab the first 100 rows for you to browse below. This ‘Preview Row Limit’ defines how many rows you can use to verify the IMPORT as we step through the wizard. You can increase it, but that will take more resources, so don’t go crazy.

Also, does your Excel file have column headers? Do we want to treat those as a row to the table? Probably not. If you uncheck the ‘Header’ flag, the column names will become a new row in your table – and probably fail to be inserted.

Sometimes your Excel file has multiple headers, or you may need to only import a certain subset of the spreadsheet. Use the ‘Skip Rows’ option to get the right data.

Step 3: Create a script or import automatically

For this exercise the ‘Insert’ method will be used. Each row processed in the Excel file will result in an INSERT statement executed on the table we’re importing to.

If you choose ‘Insert Script’, the wizard will end with an INSERT Script in your SQL Worksheet. This is a nice alternative if you want to customize the SQL, or if you need to debug/see why the ‘Insert’ method isn’t working.

Step 4: Select the Excel Columns to be Imported

You may have an Excel file with 100 columns but your table only has 30. This is where you tell SQL Developer what columns are to be used for the import. You can also modify the column order, which may make the next step a bit easier.

Step 5: Map the Excel Columns to the Table Columns

If you’re not paying attention and just letting the wizard guide you home, then now is the time to wake up. There’s a good chance the column order of the Excel file won’t match the definition of your table. This is where you will tell SQL Developer what columns in the spreadsheet match up to what columns in the Oracle table.

And remember how we set that preview window to 100 rows? We’re peaking at the data, looking for problems as we try to fit it into your table column. If we find a problem, we’ll mark the columns with those ‘warning’ symbols.

I’ve polluted my Excel file with some values that I know won’t ‘fit.’ When these rows are encountered in the wizard, they’ll be rejected by the database – but the other rows will come in.

Let’s talk about DATES for a second.

And TIMESTAMPS too. In the excel file, you’re probably going to have some date/time fields you want to move into DATE or TIMESTAMP columns. SQL Developer is treating those value as strings – and YOU need to tell SQL Developer the DATE or TIMESTAMP format to use to be able to convert them.

Let’s look at HIREDATE.

That ‘ha ha’ value will never make it in as a HIRE_DATE value – unless you’re storing DATES in a VARCHAR2 – and if you’re doing that, you’re doing it WRONG. Always store DATES as a DATE!

See the ‘Format’ drop down selector? SQL Developer has defaulted the DATE format string to ‘DD-MON-RR’ – we try to guess based on the rows we’re looking at in that 100 preview window.

If we have guessed wrong, or were unable to figure it out, you’ll need to input this yourself. The Oracle Docs can help you define the correct DATE Format Model. If you see the little warning graphics next to your Date values in the Data panel, you might have the wrong format.

Step 6: Verify your settings and GO!

Click on the ‘Finish’ button.

If the Wizard runs into any problems doing the INSERTs, you’ll see this:

Remember that funny data i put into the Excel file? That’s causing problems now.

I’m going to say ‘Yes’ to ignore all the errors. But, if you need EVERY single row – you need to say ‘Cancel’ to start over. Then you can either fix your data in the Excel file, or make changes to your table so the data will fit/work.

After clicking ‘Yes’, we’ll get to the end of our story, and our data!

Step 7: See What Worked and What Didn’t

First, any bad news?

If there were rows rejected by the database, we’ll see those now.

Behind that dialog are the INSERT statements we tried to run, but didn’t work. You might be able to edit those manually to fix a few records. But if you have thousands of rejected rows – better to fix at the source.

Now let’s go look at our new table data!

I love the sweet smell of data in the morning!

Note the ‘Log’ panel. We’ll show you the file we worked with, and how much time it took to load the data.

Just a few more pointers when it comes to Excel

  • Storing data in Excel can be…dangerous
  • If you have a lot of data or if this will be a repeating process, consider External Tables or SQL*Loader instead
  • If you like to put data in Oracle because you understand SQL better than Excel macros, then welcome to the club 😉
  • Here’s 11 more tips on Importing Excel/CSV into your database

The Movie

Источник

How to insert data directly from Excel to Oracle Database

I would like to know how to insert data from Excel to Oracle meaning lets say i have a worksheet full of data and i want to insert them all into Oracle database.

how do i do that?

thanks in advance.

5 Answers 5

Many Oracle IDEs offer this feature.

Oracle SQL Developer:

  • imports from CSV to a new or existing table
  • imports from XLS/XLSX files to a new or existing table
  • can setup an External Table or SQL*Loader session to import from a delimited file to a new or existing table
  • offers a command-line interface for automation purposes

I talk about these features here.

You can use sql loader, but if you want a more robust solution (especially if the data will be modified directly in the spreadsheet) then look into external tables in Oracle. You can build a database table directly from the spreadsheet, the code looks like this:

Note that anything with the word «your» in it above must be changed to whatever you want to name your files and directories. Also note that «YOUR_DIRECTORY» is an actual database object you must create:

Try creating Insert query in Excel(if data is not that huge):
like :
in AA1 cell write : ‘INSERT INTO

these are sample queries, plz write your own queries according to your requirement for INSERT STATEMENT.

I am just copying the approach what worked for me from above link

In Oracle sql developer go to Tables —> select import data —> select your excel or csv file —> it will display the column —> import the data into a table.

convert your excel file format to .csv format with using save as option

Save below content in a file with .ctl extension in the D drive under folder_name folder. Before running this .ctl make sure that table should be present in your schema with the distinct column names not like in your posted image. And the column name should be match with names of .ctl file(sc_id, sal, etc). And the datatypes of your columns should be match with the data present in a .csv file. And also make sure that your table should be empty otherwise you should use truncate or append options in your .ctl file.

Run your .ctl file in sql plus with use of below commands

Источник

This chapter describes how to export (unload) from and import (load) into Oracle Database XE. You can export and import metadata (database object definitions), data, or both metadata and data. It contains the following topics:

Data can be exported for later importing (loading) into another Oracle database or into a non-Oracle database. Data that has been unloaded from a non-Oracle database can be loaded into an Oracle database, if the data is in a suitable format for loading.

This chapter includes the following topics:

For convenience and the range of features available, you may want to use SQL Developer for export and import operations unless you need to use another tool (command-line utility).

Using SQL Developer for Exporting and Importing

SQL Developer provides convenient wizards for exporting and importing metadata and data:

To export metadata or data, or both, use the Export Wizard: click Tools , then Database Export .

To import metadata or data, or both, use an appropriate method depending on how the material to be imported was created, or the format of the data to be imported. This method might be running a script file, or using the Data Import Wizard to import from a data file (such as a .csv file or a Microsoft Excel .xls file).

See the following examples of using SQL Developer for performing export and import operations:

Example: Exporting Metadata and Data for a Table

Assume that you want to export the REGIONS table, which is part of the HR sample schema, so that it can be created, along with its data, in another schema (either in the same Oracle database or another Oracle database).

To unload the REGIONS table:

In SQL Developer, click Tools, then Database Export. Figure 10-1 shows the first page of the Export Wizard, but with entries reflecting selections that you will make.

Figure 10-1 Export Wizard: Source/Destination


Description of «Figure 10-1 Export Wizard: Source/Destination»

Accept the default values for the Source/Destination page options, except as follows:

Connection : Select HR .

Show Schema : Deselect (uncheck) this option, so that the HR schema name is not included in CREATE and INSERT statements in the .sql script file that will be created. (This enables you to re-create the table in a schema with any name, such as one not named HR.)

Save As location: Enter or browse to a desired folder on your local hard drive, and specify the file name for the script file. (In the figure, this file is C:tempexport.sql .) The script file containing CREATE and INSERT statements will be created in this location.

For explanations of the options on this or any other wizard page, click the Help button.

For example, Format has other possible values besides the default insert , which causes SQL INSERT statements to be included to insert the data. Other values include loader to cause SQL*Loader files to be created, and xls to cause a Microsoft Excel .xls file to be created.

On the Types to Export page, deselect Toggle All, then select only Tables (because you only want to export a table).

On the Specify Objects page, click Lookup, then double-click the REGIONS table on the left to move it to the right-hand column. Figure 10-2 shows the result of these actions.

Figure 10-2 Export Wizard: Specify Objects


Description of «Figure 10-2 Export Wizard: Specify Objects»

On the Specify Data page, accept the defaults and click Next .

By default, all data from the specified table or tables is exported; however, if you want to limit the data to be exported, you can specify one or more » WHERE clauses» in the bottom part of this page.

On the Summary page, review the information; and if it is what you want, click Finish . (Given what you specified, this causes the export script to be created as C:tempexport.sql .)

If you need to make any changes, go back to the appropriate page or pages and make them, and then move forward to the Summary page again.

Example: Importing Metadata and Data Using a Script File

Assume that you wanted to re-create the REGIONS table that you exported in «Example: Exporting Metadata and Data for a Table», but in a different schema. This other schema can be an existing one or one that you create.

For example, assume that you created a user named NICK following the instructions in «Example: Creating a User». To re-create the REGIONS table in the schema of user NICK by invoking the script in C:tempexport.sql follow these steps using SQL Developer:

If you have not already created a database connection for NICK , create the connection.

Open the NICK connection.

In the SQL Worksheet for the NICK connection, type the following:

Click the Run Script icon.

The Script Output pane shows that the REGIONS table has been created and four rows have been inserted.

In the Connections navigator, expand the Tables node under the NICK connection. You now see the REGIONS table.

Optionally, click the REGIONS table in the Connections navigator, and examine the information under the Columns and Data tabs in the main display area.

Example: Exporting Data to a Microsoft Excel File

Assume that you want to export only the data from the REGIONS table, which is part of the HR sample schema, so that the data can be imported into a table with the same column definitions. This might be a REGIONS table in another schema (either in the same Oracle database or another Oracle database).

You use the same Database Export wizard, but export only the data, and not the DDL (Data Definition Language statements for creating database objects).

To export the data the REGIONS table:

In SQL Developer, click Tools, then Database Export. Figure 10-3 shows the first page of the Export Wizard, but with entries reflecting selections that you will make.

Figure 10-3 Export Wizard: Source/Destination Specifying Data Export Only


Description of «Figure 10-3 Export Wizard: Source/Destination Specifying Data Export Only»

Accept the default values for the Source/Destination page options, except as follows:

Connection : Select HR .

Export DDL: Deselect (uncheck) this option. If a .sql script file is generated (which will not happen in this example), it will not contain any CREATE statements, but only INSERT statements.

Format : Select xls to have the data saved to a Microsoft Excel .xls file.

Save As location: Enter or browse to a desired folder on your local hard drive, and specify the file name for the .xls file. (In the figure, this file is C:tempexport.xls .)

On the Types to Export page, deselect Toggle All, then select only Tables (because you only want to export data for a table).

On the Specify Objects page, click Lookup , then double-click the REGIONS table on the left to have it appear in a row in the bottom part of the page. Figure 10-2 shows the result of these actions.

Figure 10-4 Export Wizard: Specify Objects for Exporting Data


Description of «Figure 10-4 Export Wizard: Specify Objects for Exporting Data»

By default, all data from the specified table or tables is exported; however, if you want to limit the data to be exported, you can specify one or more » WHERE clauses» in the bottom part of this page.

On the Summary page, review the information; and if it is what you want, click Finish . (Given what you specified, this causes the data in the REGIONS table to be exported to the file C:tempexport.xls .)

If you need to make any changes, go back to the appropriate page or pages and make them, and then move forward to the Summary page again.

Example: Importing Data from a Microsoft Excel File

Assume that you wanted to import the data that was exported in «Example: Exporting Data to a Microsoft Excel File», into a new table that has the same column definitions as the original ( REGIONS ) table.

For example, assume that you created a user named NICK following the instructions in «Example: Creating a User». This user wants to take the exported data, add one row in the Excel file, and import it into a new table that has the same column definitions as the REGIONS table. (This example is trivial, and adding a row to the Excel file may not be typical, but it is presented merely to illustrate some capabilities.)

To accomplish these goals, follow these steps:

In SQL Developer, if you have not already created a database connection for NICK , create the connection.

Open the NICK connection.

In the SQL Worksheet for the NICK connection, type the following:

Click the Run Script icon.

The Script Output pane shows that the NEW_REGIONS table has been created.

In the Connections navigator, expand the Tables node under the NICK connection. You now see the NEW_REGIONS table.

If you do not see the NEW_REGIONS table, disconnect from NICK (right-click NICK in the Connections navigator and select Disconnect) and connect again, and expand the Tables node.

Using Microsoft Excel, open the file containing the exported data (for example, c:tempexport.xls), and optionally add one or more rows.

Figure 10-5 shows the original file with one row added for the Antarctica region.

Figure 10-5 Microsoft Excel File with Exported Data (Modified)


Description of «Figure 10-5 Microsoft Excel File with Exported Data (Modified)»

Save and close the Microsoft Excel .xls file.

In SQL Developer, in the Connections navigator display for NICK , right-lick the NEW_REGIONS table and select Import Data .

In the dialog box that is displayed, navigate to the c:temp folder, select export.xls , and click Open .

In the Data Import Wizard, accept all the defaults; click Next on each page until Summary, and click Finish there. (For information about the options on any wizard page, click the Help button.)

The data from the .xls file is loaded into the NEW_REGIONS table and is committed.

If the SQL Developer export and import wizards are not satisfactory for your needs, you can use one of the command-line utilities available with Oracle Database XE. These other tools are described in the following sections:

Choosing the Right Export/Import Utility

Oracle Database XE provides a number of powerful utilities for exporting and importing data. Table 10-1 provides a summary of these options.

Table 10-1 Summary of Other Export/Import Data Options

VALUES(‘ then respective values from different cells(i.e. ‘A1,’+’B1,’. +’)’) it will create Insert scripts in excel. Just copy the scripts and execute.

Command-line interface, invoked with sqlldr command

Bulk-loads data into the database from external files

Supports numerous input formats, including delimited, fixed record, variable record, and stream

Loads multiple tables simultaneously

Powerful data filtering capabilities

Data Pump Export and Data Pump Import utilities

Command-line interface, invoked with expdp and impdp commands

Exports and imports from one Oracle database to another (proprietary binary format)

Imports/exports all schema object types

Imports/exports entire database, entire schema, multiple schemas, multiple tablespaces, or multiple tables

Powerful data filtering capabilities

Does not support XMLType data

Export and Import utilities

Command-line interface, invoked with exp and imp commands

Exports and imports from one Oracle database to another (proprietary binary format)

Supports XMLType data

Does not support the FLOAT and DOUBLE data types

Capabilities similar to Data Pump; Data Pump is preferred unless you must import or export XMLType data

Table 10-2 provides a number of load/unload/import/export scenarios and suggests the appropriate option to use for each.

Table 10-2 Import/Export Scenarios and Recommended Options

Feature or Utility Description

You have to load data that is not delimited. The records are fixed length, and field definitions depend on column positions.

You have tab-delimited text data to load, and there are more than 10 tables.

You have text data to load, and you want to load only records that meet certain selection criteria (for example, only records for employees in department number 3001).

You want to import or export an entire schema from or to another Oracle database. There is no XMLType data in any of the data.

Data Pump Export and Data Pump Import

You want to import or export data from or to another Oracle database. The data contains XMLType data and contains no FLOAT or DOUBLE data types.

Import ( imp ) and Export ( exp )

Oracle Database Utilities for more information on Data Pump, the Import and Export utilities, and SQL*Loader

Loading Data with SQL*Loader

SQL*Loader loads data from external datafiles into tables of an Oracle database. A particular datafile can be in fixed record format, variable record format, or stream record format (the default).

The input for a typical SQL*Loader session is a contr ol file, which controls the behavior of SQL*Loader, and some data, located either at the end of the control file itself, or in a separate datafile.

The output of a SQL*Loader session is an Oracle database (where the data is loaded), a log file, a «bad» file, and potentially, a discard file. The log file contains a detailed summary of the load, including a description of any errors that occurred during the load. The bad file contains records that were rejected, either by SQL*Loader or by the Oracle database. The discard file contains records that were filtered out of the load because they did not match any reco rd-selection criteria specified in the control file.

Methods SQL*Loader Uses to Load Data

SQL*Loader uses three different methods to load data, depending on the situation: conventional path, direct path, and external tables.

A conventional path load is the default loading method. It executes SQL INSERT statements to populate tables in an Oracle database. This method can sometimes be slower than other methods because extra overhead is added as SQL statements are generated, passed to Oracle, and executed. It can also be slower because when SQL*Loader performs a conventional path load, it competes equally with all other processes for buffer resources.

A direct path load does not compete with other users for database resources. It eliminates much of the Oracle database overhead by formatting Oracle data blocks and writing them directly to the database files, bypassing much of the data processing that normally takes place. Therefore, a direct path load can usually load data faster than conventional path. However, there are several restrictions on direct path loads that may require you to use a conventional path load. For example, direct path load cannot be used on clustered tables or on tables for which there are transactions pending.

See Oracle Database Utilities for a complete discussion of situations in which direct path load should and should not be used.

An external table load creates an external table for data that is contained in a datafile. The load executes INSERT statements to insert the data from the datafile into the target table. An external table load allows modification of the data being loaded by using SQL functions and PL/SQL functions as part of the INSERT statement that is used to create the external table.

See Oracle Database Administrator’s Guide for more information on external tables.

SQL*Loader Features

You can use SQL*Loader to do the following:

Load data across a network. This means that you can run the SQL*Loader client on a different system from the one that is running the SQL*Loader server.

Load data from multiple data files during the same load session.

Load data into multiple tables during the same load session.

Specify the character set of the data.

Selectively load data (you can load records based on the records’ values).

Manipulate the data before loading it, using SQL functions.

Generate unique sequential key values in specified columns.

Use the operating system’s file system to access the datafiles.

Load data from disk, tape, or named pipe.

Generate sophisticated error reports, which greatly aid troubleshooting.

Load arbitrarily complex object-relational data.

Use secondary datafiles for loading LOBs and collections.

Example: Using SQL*Loader

In the following example, a new table named dependents will be created in the HR sample schema. It will contain information about dependents of employees listed in the employees table of the HR schema. After the table is created, SQL*Loader will be used to load data about the dependents from a flat data file into the dependents table.

This example requires a data file and a SQL*Loader control file, which you will create in the first two steps.

Create the data file, dependents.dat , in your current working directory. You can create this file using a variety of methods, such as a spreadsheet application or by simply typing it into a text editor. It should have the following content:

This file is a CSV (comma-separated values) file in which the commas act as delimiters between the fields. The field containing the first name is enclosed in double quotation marks in cases where a variant of the official name is also provided—that is, where the first name field contains a comma.

Create the SQL*Loader control file, dependents.ctl , in your current working directory. You can create this file with any text editor. It should have the following content:

Do one of the following:

On Linux: Start a terminal session and log in to the Oracle Database XE host computer with the oracle user account.

On Windows: Log in to the Oracle Database XE host computer as the user who installed Oracle Database XE, and then open a command window.

On Linux, ensure that environment variables are set according to the instructions in «Setting Environment Variables on the Linux Platform».

Start the SQL Command Line (SQL*Plus) and connect as user hr by entering the following at the command prompt:

At the SQL prompt, create the dependents table, as follows:

The constraint on the last_name column indicates that a value must be provided. The constraint on the relative_id column indicates that it must match a value in the employee_id column of the employees table. The benefits column has a datatype of CLOB so that it can hold large blocks of character data. (In this example, there is not yet any benefits information available so the column is shown as NULL in the data file, dependents.dat .)

After you receive the Table created message, enter exit to exit the SQL Command Line.

From within your current working directory (where you created the control and data files), issue the following SQL*Loader command at the system prompt:

The data in the dependents.dat file is loaded into the dependents table and the following message is displayed:

Information about the load is written to the log file, dependents.log . The content of the log file looks similar to the following:

You can now work with the dependents table, as you would any other table.

Exporting and Importing Data

Oracle Database XE provides the following command-line utilities for exporting and importing data:

Data Pump Export and Data Pump Import

Export and Import

The following sections provide an overview of each utility. For a summary of when you might want to use each utility, see Table 10-2.

Oracle Database Utilities for detailed information on these utilities, including command line parameter descriptions and additional examples.

Exporting and Importing with Data Pump Export and Data Pump Import

The Data Pump Export utility exports data and metadata into a set of operating system files called a dump file set . The Data Pump Import utility imports an export dump file set into a target Oracle database.

A dump file set is made up of one or more disk files that contain table data, database object metadata, and control information. The files are written in a proprietary, binary format, which means that the dump file set can be imported only by the Data Pump Import utility. The dump file set can be imported to the same database or it can be moved to another system and loaded into the Oracle database there.

Because the dump files are written by the database, rather than by the Data Pump client application, you must create directory objects for the directories to which files will be written. A directory object is a da tabase object that is an alias for a directory in the host operating system’s file system.

Data Pump Export and Import enable you to move a subset of the data and metadata. This is done by using Data Pump parameters to specify export and import modes, as well as various filtering criteria.

You can also perform exports and imports over a network. In a network export, the data from the source database instance is written to a dump file set on the connected database instance. In a network import, a target database is loaded directly from a source database with no intervening dump files. This allows export and import operations to run concurrently, minimizing total elapsed time.

Data Pump Export and Import also provide a set of interactive commands so that you can monitor and modify ongoing export and import jobs.

Data Pump Export and Data Pump Import do not support XMLType data. If you need to export and import XMLType data, use the Export and Import options described in «Exporting and Importing Data with the Export and Import Utilities».

Example: Using Data Pump Export and Data Pump Import

In this example, suppose that you want to make some changes to the HR sample schema and then test those changes without affecting the current HR schema. You could export the HR schema and then import it into a new HRDEV schema, where you could perform development work and conduct testing. To do this, take the following steps:

Do one of the following:

On Windows: Log in to the Oracle Database XE host computer as the user who installed Oracle Database XE, and then open a command window.

On Linux: Start a terminal session and log in to the Oracle Database XE host computer with the oracle user account.

On Linux, ensure that environment variables are set according to the instructions in «Setting Environment Variables on the Linux Platform».

At the command prompt, issue the command appropriate to your operating system, to create the directory where the exported files will be placed:

Start the SQL Command Line (SQL*Plus) and connect as user SYSTEM by entering the following at the command prompt:

where password is the password that you specified for the SYS and SYSTEM user accounts upon installation (Windows) or configuration (Linux) of Oracle Database XE.

At the SQL prompt, enter the following commands to create a directory object named dmpdir for the tmp directory that you just created, and to grant read and write access to it for user HR .

Export the HR schema to a dump file named schema.dmp by issuing the following command at the system command prompt:

where password is the password for the SYSTEM user.

As the export operation takes place, messages similar to the following are displayed:

The schema.dmp file and the expschema.log file are written to the dmpdir directory.

Import the dump file, schema.dmp , into another schema, in this case, HRDEV . You use the REMAP_SCHEMA command parameter to indicate that objects are to be imported into a schema other than their original schema. Because the HRDEV user account does not already exist, the import process automatically creates it. In this example, you will import everything except constraints, ref_constraints, and indexes. If a table already exists, it is replaced with the table in the export file.

At the operating system command prompt, issue the following command:

where password is the password for the SYSTEM user.

As the import operation takes place, messages similar to the following are displayed (this output is also written to the impschema.log file in the dmpdir directory):

The HRDEV schema is now populated with data from the HR schema.

Assign a password to the newly created HRDEV user account. To do so, start the SQL Command Line and connect as user SYSTEM (as you did in step 4), and then at the SQL prompt, enter the following ALTER USER statement:

This statement assigns the password hrdev .

You can now work in the HRDEV schema without affecting your production data in the HR schema.

Exportin g and Importing Data with the Export and Import Utilities

The Export and Import utilities provide a simple way for you to transfer data objects between Oracle databases. They are invoked with the exp and imp commands, respectively. These utilities provide support for XMLType data, whereas the Data Pump Export and Import utilities do not.

The Export and Import utilities do not support the FLOAT and DOUBLE data types. If your data contains these types and does not contain XMLType data, you must use Data Pump Export and Import, described in «Exporting and Importing with Data Pump Export and Data Pump Import».

When you run the Export utility against an Oracle database, objects (such as tables) are extracted, followed by their related objects (such as indexes, comments, and grants), if any. The extracted data is written to an export dump file. The dump file is an Oracle binary-format dump file that can be read only by the Import utility. The version of the Import utility cannot be earlier than the version of the Export utility used to create the dump file.

Dump files generated by the Export ( exp ) utility can only be imported by the Import ( imp ) utility; they cannot be imported with the Data Pump Import ( impdp ) utility.

Like Data Pump Import and Export, data exported with the Export utility can be imported with the Import utility into the same or a different Oracle database.

See Oracle Database Utilities for further information about the Export and Import utilities and for examples of how to use them.

Источник

Adblock
detector

Import/Export Scenario Recommended Option

It was late. In a corner of the Treasury however, a light burned brightly.
Phillip Hammond, Chancellor of the Exchequer, was still working.
“Spreadsheet Phil” was trying to formulate a plan to rectify the nation’s finances in the event that the Prime Minister was won over by the ebullient Mr Johnson and decided upon a “No Deal” Brexit.
Boris Johnson was currently based at the F.O. which, Phil considered darkly, was somewhat appropriate.
If only his predecessor had had the foresight to stick a couple of billion on Liecester City to win the league at 5000 to 1, The Country’s finances would be in much better shape.
In the midst of this gloomy reflection, he was struck by a sudden inspiration. The crowded half-hour that followed resulted in – what else – a spreadsheet.
The information therein could save The Economy. “Hmmm”, thought Phil, “this stuff is far too important to leave in Excel, I really need to put it into my Oracle database. I wonder if SQLDeveloper could help”…

Being a cautious soul, Phil has decided to stick with something he knows quite well – the question of who is going to be the next Prime Minister of the United Kingdom of Great Britain and Northern Ireland including (for the moment at least), Scotland :

The workbook consists of two sheets – Party Leaders and Odds. At this stage, Phil just wants to upload the data in the Odds sheet.
The data in the decimal odds column is derived by means of a formula, for example :

=E3/F3

As we will see, SQLDeveloper will upload the values in cells rather than any formulas that may be present.

The observant among you will also notice that the above screenshot is taken from Libre Office Calc rather than Excel.

As I’m using Ubuntu at the moment, I don’t have a version of Excel to hand. This wouldn’t be much of a problem except for the fact that the SQLDeveloper version I’m using (4.2), doesn’t offer the option of importing data from an ODS formatted spreadsheet.
Fortunately Calc can save a workbook in numerous formats…including XLSX.
You could pretend that the British Government has come to it’s senses and is saving billions in licensing by using open source software. However, in that scenario, we’d probably be using a different RDBMS so it looks like you’re stuck with the real politik of the situation.

Anyhow, this is our spreadsheet. It is in XLSX (Excel 2003 or later) format. We want to load the data from one of it’s two Worksheets into an Oracle database table…

The target table

The DDL for the target table is :

create table next_pm(
    first_name varchar2(100) not null,
    last_name varchar2(100) not null,
    decimal_odds number,
    date_elected date
)
/

…and there is already some data in it :

select first_name, last_name, decimal_odds, 
    to_char(date_elected, 'fmddth Month YYYY') as "Elected to Parliament"
from next_pm
/

FIRST_NAME                     LAST_NAME                      DECIMAL_ODDS Elected to Parliament                         
------------------------------ ------------------------------ ------------ ----------------------------------------------
Phillip                        Hammond                                3.33 1st May 1997                                  

You’ll notice that the table does not contain the same columns as the spreadsheet does. The columns it does have in common with the spreadsheet are in a different order.
Oh, and they have names that are different from the headings in the spreadsheet.
As Phil is about to find out, all of these potential problems can be easily overcome…

The SQLDeveloper Import Data Wizard

Firing up SQLDeveloper, Phil navigates to the NEXT_PM table.
Now, he could just use the right-click menu in the Tree view on the left of the screen, but he prefers to select the table and then invoke the Actions menu…

…and selecting Import Data…, which invokes the Data Import Wizard…

When Phil selects his spreadsheet, SQLDeveloper defaults to the first Worksheet. For some reason, it also insists on defaulting the file format to Excel 95-2003 (xls)

…that’s easily changed, and Phil selects the appropriate Excel format before hitting the Worksheet drop-down to pick the appropriate worksheet

At first, SQLDeveloper isn’t too sure of about the column headings….

…but Phil just sets Skip Rows to 1 and…

Now Phil is happy with what he sees, he clicks Next

He then has a choice of Import methods. He could just opt to create an Insert script by setting the Input Method to Insert Script. Breaking the habit of a lifetime however, Phil throws caution to the wind and decides to Insert the data directly into the table. By leaving Send create script to SQL Worksheet checked, he’ll get an insert script anyway.

Time to click Next.

By default, all of the columns in the Worksheet are selected. Phil uses the left and right arrow buttons to choose only the columns that he wants to import into the table, and then the up and down arrows to specify the order …

Now, he clicks Next.

What he notices here are the red exclamation marks. SQLDeveloper is smart enough to point out that there are some issues to be sorted out…

Phil has a couple of options here. By clicking on a Source Data Column that has a red exclamation mark he can see information such as a Status explaining why the column has been marked by SQLDeveloper, the target column this data is currently pointing to in the target table, and even a sample of the data contained in the column…

He can then take the appropriate action to fix the problem. In this case, he could for example, specify that the Decimal column in the spreadsheet should be imported into the DECIMAL_ODDS table column.
However, as he’s just gone to all that trouble to get his columns in the correct order in the previous screen, he simply changes the Match By drop-down value from Name to Position :

Phil has one last little glitch to sort out, as can be seen from the Yellow exclamation mark on the DATE_ELECTED_AS_AN_MP source column.
In this case, it’s simply a question of setting an appropriate date format…

…and clicking Next

Finally, Phil has the opportunity to review his settings…

…and then, when he’s happy, hit the Finish button to import the data.

At this point, SQLDeveloper displays this reassuring message :

Now Phil can see that the data has been successfully loaded into the table whilst preserving the pre-existing record :

“Well”, thought Phil to himself, “I never knew that getting data from Excel into Oracle was so simple. Now, back to Brexit, it can’t be that hard…”

SQL Developer is an increasingly important tool. I’ve known it since it first came out and in each new release they get things more and more powerful. I have also seen that many people who use it do not exploit more than 10 -20% of the capabilities of the tool.

Perhaps the main disadvantage that SQL Developer has is that it is programmed in JAVA, which makes it portable between different Operating Systems, but penalizes performance and memory consumption. This tool developed in c could be incredible, but it would imply porting to each platform it supports.

Today I just want to show a feature that has saved me hours of work when importing excel sheets into an Oracle database. Of course, using Microsoft Office or LibreOffice you can open a connector to the database and do the same.

Let’s see the steps

On table, click rigth button and select “Import Data”;

import_sql_dev_1

The next window appears. Here click on Browse and choose the xlsx file

import_sql_dev_2

In this case we will make the insertion as individual inserts, click on “Next”;

import_sql_dev_3

In my case I selected all columns to import. Click on “Next”;

import_sql_dev_4

In this case it is matched by name, click on “Next”;

import_sql_dev_5

In this phase of the process we are shown a summary of all the steps. Click on “Finish”;

import_sql_dev_6

If everything went well we will see a window like this;

import_sql_dev_7

HTH – Antonio NAVARRO

Like this post? Please share to your friends:
  • Oracle sql and excel
  • Oracle smart view excel
  • Oracle odbc driver 64 bit excel
  • Oracle external table excel
  • Oracle excel to database