I’m trying to import a .txt file into PostgreSQL. The txt file has 6 columns:
Laboratory_Name Laboratory_ID Facility ZIP_Code City State
And 213 rows.
I’m trying to use copy to put the contents of this file into a table called doe2 in PostgreSQL using this command:
copy DOE2 FROM '/users/nathangroom/desktop/DOE_inventory5.txt' (DELIMITER(' '))
It gives me this error:
missing data for column "facility"
I’ve looked all around for what to do when encountering this error and nothing has helped. Has anyone else encountered this?
asked Nov 5, 2014 at 0:33
2
Three possible causes:
-
One or more lines of your file has only 4 or fewer space characters (your delimiter).
-
One or more space characters have been escaped (inadvertently). Maybe with a backslash at the end of an unquoted value. For the (default)
textformat you are using, the manual explains:
Backslash characters (
) can be used in theCOPYdata to quote data
characters that might otherwise be taken as row or column delimiters.
Output from COPY TO or pg_dump would not exhibit any of these faults when reading from a table with matching layout. But maybe your file has been edited or is from a different, faulty source?
- You are not using the file you think you are using. The
copymeta-command of the psql command-line interface is a wrapper forCOPYand reads files local to the client. If your file lives on the server, use the SQL commandCOPYinstead.
answered Nov 5, 2014 at 1:30
Erwin BrandstetterErwin Brandstetter
577k139 gold badges1034 silver badges1188 bronze badges
7
Check the file carefully. In my case, a blank line at the end of the file caused the ERROR: missing data for column. Deleted it, and worked fine.
Printing the blank lines might reveal something interesting:
cat -e $filename
answered Oct 13, 2021 at 16:17
NagevNagev
9,2354 gold badges52 silver badges65 bronze badges
I had a similar error. check the version of pg_dump that was used in exporting the data and the version of the database you are want to insert it into. make sure they are same. Also, if copy export fails then export the data by insert
answered Jan 2, 2022 at 21:20
![]()
aniefiokaniefiok
211 silver badge5 bronze badges
I’m trying to import a .txt file into PostgreSQL. The txt file has 6 columns:
Laboratory_Name Laboratory_ID Facility ZIP_Code City State
And 213 rows.
I’m trying to use copy to put the contents of this file into a table called doe2 in PostgreSQL using this command:
copy DOE2 FROM '/users/nathangroom/desktop/DOE_inventory5.txt' (DELIMITER(' '))
It gives me this error:
missing data for column "facility"
I’ve looked all around for what to do when encountering this error and nothing has helped. Has anyone else encountered this?
asked Nov 5, 2014 at 0:33
2
Three possible causes:
-
One or more lines of your file has only 4 or fewer space characters (your delimiter).
-
One or more space characters have been escaped (inadvertently). Maybe with a backslash at the end of an unquoted value. For the (default)
textformat you are using, the manual explains:
Backslash characters (
) can be used in theCOPYdata to quote data
characters that might otherwise be taken as row or column delimiters.
Output from COPY TO or pg_dump would not exhibit any of these faults when reading from a table with matching layout. But maybe your file has been edited or is from a different, faulty source?
- You are not using the file you think you are using. The
copymeta-command of the psql command-line interface is a wrapper forCOPYand reads files local to the client. If your file lives on the server, use the SQL commandCOPYinstead.
answered Nov 5, 2014 at 1:30
Erwin BrandstetterErwin Brandstetter
577k139 gold badges1034 silver badges1188 bronze badges
7
Check the file carefully. In my case, a blank line at the end of the file caused the ERROR: missing data for column. Deleted it, and worked fine.
Printing the blank lines might reveal something interesting:
cat -e $filename
answered Oct 13, 2021 at 16:17
NagevNagev
9,2354 gold badges52 silver badges65 bronze badges
I had a similar error. check the version of pg_dump that was used in exporting the data and the version of the database you are want to insert it into. make sure they are same. Also, if copy export fails then export the data by insert
answered Jan 2, 2022 at 21:20
![]()
aniefiokaniefiok
211 silver badge5 bronze badges
|
0 / 0 / 0 Регистрация: 18.01.2016 Сообщений: 9 |
|
|
1 |
|
Загрузка данных в таблицу12.04.2020, 18:44. Показов 2067. Ответов 1
Здравствуйте. Заполнение делаю через импорт в pgadmin. Файл приложил, но только excel, csv почему — то не загружает, но в нем по типам данных всё то же самое.
__________________
0 |
|
1184 / 914 / 367 Регистрация: 02.09.2012 Сообщений: 2,785 |
|
|
13.04.2020, 07:44 |
2 |
|
Помогите пожалуйста понять в чем причина. Посмотрите, что там в 105 строке в файле. Добавлено через 11 минут
0 |
В настоящее время я работаю над созданием автоматизированного генератора таблиц в Mathematica, который берет большой csv и разбивает его пополам, чтобы избежать ограничения столбцов в таблицах в Postgres.
Я проинструктировал таблицы, чтобы каждый столбец принимал нулевые значения из-за пустых столбцов здесь и там, но когда я отправляю команду copy, он действует и жалуется, что некоторые столбцы пусты в самом конце 2-го файла.
Ранее в CSV-файле есть другие пустые столбцы, на которые он не жалуется, и редактирование рассматриваемого столбца в CSV-файле также не устраняет (или не изменяет) ошибку.
Текущая команда гласит:
psql -c copy table_name FROM 'file_pathfile_name.csv' WITH DELIMITER ',' NULL '' CSV HEADER
Ошибка гласит:
Ошибка: отсутствуют данные для столбца «имя_столбца»
Контекст: COPY имя_таблицы, строка 2: «1,2,3,…»
2 ответа
После небольшого поиска количество столбцов в таблице действительно не соответствует количеству в csv. Это означает, что список имен столбцов, который мне предоставили (из CSV-файла, который давал сводную информацию о том, для чего предназначен каждый столбец), включал те, которые не были оставлены пустыми, но даже не использовались в основном файле.
Это я могу просто обвинить в небрежности поставщика данных и обойти это.
Но я сбит с толку, почему для их заполнения потребовались другие столбцы вместо значений по умолчанию или NULL, а затем ничего не осталось для нескольких столбцов в конце. Я думал, что он заполнил столбцы, сопоставив их заголовки между таблицей и CSV?
0
ChaosKing1236
28 Май 2021 в 20:40
Вы получите эту ошибку, если копируете в таблицу, в которой больше полей, чем в csv. В этом случае вам нужно указать поля CSV в порядке, указанном в заголовке файла.
Итак, если в строке заголовка вашего файла есть Field1,Field2,Field3, вы можете скопировать его в таблицу с полями Field1, Field2, Field3 и Field4, например это
psql -h mydbhost -c "copy "MyTable"("Field1","Field2","Field3") from 'yourfile.csv' csv header"
Я использовал в примере поля с учетом регистра в кавычках; вы можете упростить его, если это не относится к вашему варианту использования.
(спасибо @JGH за то, что подтолкнул меня в правильном направлении)
0
starfry
22 Июл 2022 в 18:00
- ОБНОВЛЕНИЕ — это официальные данные, которые правительство
s offering, and it действительно уродливо. Нет UTF8, сломанные строки из того, что я вижу http://data.gov.ro/storage/f/2013-11-01T13:59:27.012Z/contracte-2007.csv Код CREATE TABLE
CREATE TABLE contracte (
castigator text,
castigatorcui text,
castigatortara text,
castigatorlocalitate text,
castigatoradresa text,
tip text,
tipcontract text,
tipprocedura text,
autoritatecontractanta text,
autoritatecontractantacui text,
tipac text,
tipactivitateac text,
numaranuntatribuire text,
dataanuntatribuire text,
tipincheierecontract text,
tipcriteriiatribuire text,
culicitatieelectronica text,
numaroferteprimite text,
subcontractat text,
numarcontract text,
datacontract text,
titlucontract text,
valoare text,
moneda text,
valoareron text,
valoareeur text,
cpvcodeid text,
cpvcode text,
numaranuntparticipare text,
dataanuntparticipare text,
valoareestimataparticipare text,
monedavaloareestimataparticipare text,
fonduricomunitare text,
tipfinantare text,
tiplegislatieid text,
fondeuropean text,
contractperiodic text,
depozitegarantii text,
modalitatifinantare text
);
Код SQL
COPY contracte(Castigator,CastigatorCUI,CastigatorTara,CastigatorLocalitate,
CastigatorAdresa,Tip,TipContract,TipProcedura,AutoritateContractanta,
AutoritateContractantaCUI,TipAC,TipActivitateAC,NumarAnuntAtribuire,DataAnuntAtribuire,
TipIncheiereContract,TipCriteriiAtribuire,CuLicitatieElectronica,NumarOfertePrimite,
Subcontractat,NumarContract,DataContract,TitluContract,Valoare,Moneda,ValoareRON,
ValoareEUR,CPVCodeID,CPVCode,NumarAnuntParticipare,DataAnuntParticipare,
ValoareEstimataParticipare,MonedaValoareEstimataParticipare,FonduriComunitare,
TipFinantare,TipLegislatieID,FondEuropean,ContractPeriodic,DepoziteGarantii,
ModalitatiFinantare)
FROM 'C:\SinaiaSEAP 2007-2015contracte-2009.csv'
WITH DELIMITER '^'encoding 'WIN1252' NULL AS '/N';
Ошибка, которую я получаю:
ERROR: missing data for column "tip"
CONTEXT: COPY contracte, line 5312: "SC EUROSTRADE
SRL^7695851^Romania^Jilava^sediul social- Comuna Comana, Judetul Giurgiu"
********** Error **********
ERROR: missing data for column "tip"
SQL state: 22P04
Context: COPY contracte, line 5312: "SC EUROSTRADE SRL^7695851^Romania^Jilava^sediul social- Comuna Comana, Judetul Giurgiu"
Если я попытаюсь добавить CSV-заголовок, я получаю еще одну ошибку
ERROR: extra data after last expected column
CONTEXT: COPY contracte, line 5209: "S.C. ELECTRA LUC S.R.L.^12094467^Romania^Bucuresti^Bucuresti, str. Vasile Lascar nr. 165, sector 2^A..."
********** Error **********
Создаю отношение
create table ПОТРЕБИТЕЛЬ (
ИДЕНТИФИКАТОР serial not null primary key,
НАЗВАНИЕ varchar(50) not null,
"АДРЕС ЖИТЕЛЬСТВА" varchar(255) not null,
"СКИДКА, %" smallint check ("СКИДКА, %" >= 0 and "СКИДКА, %" <= 100) not null
);
Затем пытаюсь заполнить таблицу, используя значения
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (001, "АО ВАРЯ", "Сормовский", 10);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (002, "ГАЗ", "Автозаводский", 7);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (003, "МП ВЕРА", "Канавинский", 5);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (004, "МП", "Канавинский", 3);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (005, "АО СТАЛЬ", "Советский", 0);
Возникает ошибка в каждой строчке, якобы столбец не существует, при этом это даже не столбцы а аргументы

