после запроса COPY objrts FROM 'C:objrt00100.unl' (DELIMITER '|');
не знаю как бороться
ОШИБКА: лишние данные после содержимого последнего столбца
CONTEXT: COPY objrts, строка 1: "11955|13124|I||93|0,0|0,0|0|0,0|0,0|0,0|0,0|0,0|0|0|2013-04-08 00:00:00|||"
задан 19 сен 2016 в 9:42
DiSayThisDiSayThis
472 серебряных знака9 бронзовых знаков
1
1 ответ
Без структуры objrts точно ответ дать не получится, но вероятнее всего у вас в строке слишком много элементов. Попробуйте убрать несколько разделителей с конца.
ответ дан 19 сен 2016 в 11:15
15.12.2019, 19:20. Показов 4200. Ответов 0
Здравствуйте, возникла проблема с импортом данных из csv файла в таблицу базы данных postgresql.
Код:
| Python | ||
|
Структура таблицы:
| SQL | ||
|
Добавлено через 8 минут
Здравствуйте, возникла проблема с импортом данных из csv файла в таблицу базы данных postgresql. Если запустить этот код , то получаю ошибку: psycopg2.errors.BadCopyFileFormat: ОШИБКА: лишние данные после содержимого последнего столбца
CONTEXT: COPY test_tomsk, строка 1: «13.12.2019 22:00;-5.2;746.8;760.2;0.8;84;Ветер, дующий с западо-северо-за…»
Код:
| Python | ||
|
Если же закомментировать 11 строку, а 12 раскомментировать, то получаю ошибку: psycopg2.errors.BadCopyFileFormat: ОШИБКА: нет данных для столбца «SSS»
CONTEXT: COPY test_tomsk, строка 1: «13.12.2019 22:00;-5.2;746.8;760.2;0.8;84;Ветер, дующий с западо-северо-за…»
В чем причина не могу понять. Csv-шник во вложении.
Структура таблицы БД следующая:
| SQL | ||
|
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
Я работаю над проектом, в котором мне нужно создать новую таблицу, а затем импортировать данные из CSV. Я прочитал много похожих вопросов («дополнительные данные после последнего ожидаемого столбца») и ответы на StackOverflow, но я все еще не нашел виновника.
CREATE TABLE colleges2014_15 (
unitid integer,
intsnm text,
city text,
stabbr text,
zip_clean char,
control integer,
latitude float,
longitude float,
tutionfee_in float,
tuitionfee_out float,
pctpell float,
inc_pct_lo float,
dep_stat_pct_ind float,
dep_debt_mdn float,
ind_debt_mdn float,
pell_debt_mdn float,
ugds_men float,
ubds_women float,
locale integer,
PRIMARY KEY(unitid)
);
Таблица создана успешно с 19 различными столбцами. Затем я пытаюсь импортировать данные в новую таблицу.
COPY colleges2014_15(
unitid,
intsnm,
city,
stabbr,
zip_clean,
control,
latitude,
longitude,
tutionfee_in,
tuitionfee_out,
pctpell,
inc_pct_lo,
dep_stat_pct_ind,
dep_debt_mdn,
ind_debt_mdn,
pell_debt_mdn,
ugds_men,
ubds_women,
locale
)
FROM '/Users/compose/Downloads/CollegeScorecard_Raw_Data x/MERGED2014_15_cleaned.csv' CSV HEADER
;
И я получаю сообщение об ошибке. Я сделал следующее в CSV:
- Убедитесь, что он сохранен как UTF-8 CSV (работает на Mac)
- Уже вычистил все запятые в каждом ряду
- Вычистил все значения NULL
- Подтверждено, что все типы данных (целые, плавающие, текстовые и т. Д.) Верны
- Я пытался просто скопировать только первый столбец,
unitid; это не удалось. Я попытался импортировать только второй столбец (intsnm), и он не удалось с той же ошибкой.
Полное сообщение об ошибке при попытке скопировать все 19 столбцов выглядит следующим образом:
Произошла ошибка при выполнении команды SQL: COPY colleges2014_15 (unitid, intsnm, город, stabbr, zip_clean, контроль, широта, долгота, tutionfee_in, tuitionfee_out, pctpell, inc_pct _…
ОШИБКА: дополнительные данные после последнего ожидаемого столбца Где: COPY colleges2014_15, строка 2: «100654, Alabama A & M University, Normal, AL, 35762,35762,1,34.783368, -86.568502,9096,16596,0,7356,0,651 … «1 заявление не удалось.
Время выполнения: 0,03 с
Полное сообщение об ошибке при попытке скопировать только первый столбец:
Произошла ошибка при выполнении команды SQL: COPY colleges2014_15 (unitid) FROM ‘/ Users / compose / Downloads / CollegeScorecard_Raw_Data x / MERGED2014_15_cleaned.csv’ CSV HEADER
ОШИБКА: дополнительные данные после последнего ожидаемого столбца Где: COPY colleges2014_15, строка 2: «100654, Alabama A & M University, Normal, AL, 35762,35762,1,34.783368, -86.568502,9096,16596,0,7356,0,651 … «1 заявление не удалось.
Время выполнения: 0,01 с
Огромная благодарность за любую помощь.
Мне потребовалось некоторое время, чтобы выяснить, что было неправильно при поиске ошибки, поэтому разместил мою проблему, чтобы помочь другим. Моя проблема заключалась в неопытности с pgAdmin, так как pgAdmin требует, чтобы таблица создавалась в столбцах WITH до импорта данных. Я ожидал, что заголовки будут использоваться из файла .csv, большинство других пакетов, которые я использовал, работали таким образом.
Если вы работаете с ГИС-системой, использующей PostGIS, есть простое решение. Я использую QGIS 3.4, с установленными Postgres и PostGIS.
В QGIS
Выберите пункт меню «База данных»
Выберите DBManager
Слева — выберите место для стола Выберите Импорт слоя / файла В следующем окне выберите следующее
Ввод — выберите файл
Таблица — введите имя таблицы
хорошо
An empty table won’t do. You need table that matches the structure of input data. Something like:
CREATE TABLE raw_data (
col1 int
, col2 int
...
);
You don’t need to declare tab as DELIMITER since that’s the default:
COPY raw_data FROM '/home/Projects/TestData/raw_data.txt';
800 columns you say? That many columns would typically indicate a problem with your design. Anyway, there are ways to half-automate the CREATE TABLE script.
Automation
Assuming simplified raw data
1 2 3 4 -- first row contains "column names"
1 1 0 1 -- tab separated
1 0 0 1
1 0 1 1
Define a different DELIMITER (one that does not occur in the import data at all), and import to a temporary staging table with a single text column:
CREATE TEMP TABLE tmp_data (raw text);
COPY tmp_data FROM '/home/Projects/TestData/raw_data.txt' WITH (DELIMITER '§');
This query creates the CREATE TABLE script:
SELECT 'CREATE TABLE tbl (col' || replace (raw, E't', ' bool, col') || ' bool)'
FROM (SELECT raw FROM tmp_data LIMIT 1) t;
A more generic & safer query:
SELECT 'CREATE TABLE tbl('
|| string_agg(quote_ident('col' || col), ' bool, ' ORDER BY ord)
|| ' bool);'
FROM (SELECT raw FROM tmp_data LIMIT 1) t
, unnest(string_to_array(t.raw, E't')) WITH ORDINALITY c(col, ord);
Returns:
CREATE TABLE tbl (col1 bool, col2 bool, col3 bool, col4 bool);
Execute after verifying validity — or execute dynamically if you trust the result:
DO
$$BEGIN
EXECUTE (
SELECT 'CREATE TABLE tbl (col' || replace(raw, ' ', ' bool, col') || ' bool)'
FROM (SELECT raw FROM tmp_data LIMIT 1) t
);
END$$;
Then INSERT the data with this query:
INSERT INTO tbl
SELECT (('(' || replace(replace(replace(
raw
, '1', 't')
, '0', 'f')
, E't', ',')
|| ')')::tbl).*
FROM (SELECT raw FROM tmp_data OFFSET 1) t;
Or simpler with translate():
INSERT INTO tbl
SELECT (('(' || translate(raw, E'10t', 'tf,') || ')')::tbl).*
FROM (SELECT raw FROM tmp_data OFFSET 1) t;
The string is converted into a row literal, cast to the newly created table row type and decomposed with (row).*.
All done.
You could put all of that into a plpgsql function, but you’d need to safeguard against SQL injection. (There are a number of related solutions here on SO. Try a search.
db<>fiddle here
Old SQL Fiddle
An empty table won’t do. You need table that matches the structure of input data. Something like:
CREATE TABLE raw_data (
col1 int
, col2 int
...
);
You don’t need to declare tab as DELIMITER since that’s the default:
COPY raw_data FROM '/home/Projects/TestData/raw_data.txt';
800 columns you say? That many columns would typically indicate a problem with your design. Anyway, there are ways to half-automate the CREATE TABLE script.
Automation
Assuming simplified raw data
1 2 3 4 -- first row contains "column names"
1 1 0 1 -- tab separated
1 0 0 1
1 0 1 1
Define a different DELIMITER (one that does not occur in the import data at all), and import to a temporary staging table with a single text column:
CREATE TEMP TABLE tmp_data (raw text);
COPY tmp_data FROM '/home/Projects/TestData/raw_data.txt' WITH (DELIMITER '§');
This query creates the CREATE TABLE script:
SELECT 'CREATE TABLE tbl (col' || replace (raw, E't', ' bool, col') || ' bool)'
FROM (SELECT raw FROM tmp_data LIMIT 1) t;
A more generic & safer query:
SELECT 'CREATE TABLE tbl('
|| string_agg(quote_ident('col' || col), ' bool, ' ORDER BY ord)
|| ' bool);'
FROM (SELECT raw FROM tmp_data LIMIT 1) t
, unnest(string_to_array(t.raw, E't')) WITH ORDINALITY c(col, ord);
Returns:
CREATE TABLE tbl (col1 bool, col2 bool, col3 bool, col4 bool);
Execute after verifying validity — or execute dynamically if you trust the result:
DO
$$BEGIN
EXECUTE (
SELECT 'CREATE TABLE tbl (col' || replace(raw, ' ', ' bool, col') || ' bool)'
FROM (SELECT raw FROM tmp_data LIMIT 1) t
);
END$$;
Then INSERT the data with this query:
INSERT INTO tbl
SELECT (('(' || replace(replace(replace(
raw
, '1', 't')
, '0', 'f')
, E't', ',')
|| ')')::tbl).*
FROM (SELECT raw FROM tmp_data OFFSET 1) t;
Or simpler with translate():
INSERT INTO tbl
SELECT (('(' || translate(raw, E'10t', 'tf,') || ')')::tbl).*
FROM (SELECT raw FROM tmp_data OFFSET 1) t;
The string is converted into a row literal, cast to the newly created table row type and decomposed with (row).*.
All done.
You could put all of that into a plpgsql function, but you’d need to safeguard against SQL injection. (There are a number of related solutions here on SO. Try a search.
db<>fiddle here
Old SQL Fiddle
-
Home -
Software Programming -
COPY in postgresql, error: extra data after the last column
This topic has been deleted. Only users with topic management privileges can see it.
-
after request
COPY objrts FROM 'C:objrt00100.unl' (DELIMITER '|');
I don’t know how to fight.ОШИБКА: лишние данные после содержимого последнего столбца
CONTEXT: COPY objrts, строка 1: "11955|13124|I||93|0,0|0,0|0|0,0|0,0|0,0|0,0|0,0|0|0|2013-04-08 00:00:00|||"
-
No structure objrts I’m sure you can’t answer, but you probably have too many elements in your line. Try to clean up a few diaries.
Suggested Topics
-
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views -
2
0
Votes2
Posts0
Views
I am working on a project where I need to create a new table, then import data from a CSV. I’ve read many similar questions («extra data after last expected column») and answers on StackOverflow, but I still haven’t found the culprit.
CREATE TABLE colleges2014_15 (
unitid integer,
intsnm text,
city text,
stabbr text,
zip_clean char,
control integer,
latitude float,
longitude float,
tutionfee_in float,
tuitionfee_out float,
pctpell float,
inc_pct_lo float,
dep_stat_pct_ind float,
dep_debt_mdn float,
ind_debt_mdn float,
pell_debt_mdn float,
ugds_men float,
ubds_women float,
locale integer,
PRIMARY KEY(unitid)
);
The table is created successfully with the 19 different columns. Then I go try to import the data into the new table.
COPY colleges2014_15(
unitid,
intsnm,
city,
stabbr,
zip_clean,
control,
latitude,
longitude,
tutionfee_in,
tuitionfee_out,
pctpell,
inc_pct_lo,
dep_stat_pct_ind,
dep_debt_mdn,
ind_debt_mdn,
pell_debt_mdn,
ugds_men,
ubds_women,
locale
)
FROM '/Users/compose/Downloads/CollegeScorecard_Raw_Data x/MERGED2014_15_cleaned.csv' CSV HEADER
;
And I get the error message. I’ve done the following in the CSV:
- Made sure it’s saved as UTF-8 CSV (working on a Mac)
- Already cleaned out all commas in every row
- Cleaned out all NULL values
- Confirmed that all the data types (integer, float, text, etc.) are correct
- I’ve tried to simply COPY only the first column,
unitid; it failed. I’ve tried importing only the second column (intsnm) and it failed with the same error.
The full error message when trying to COPY over all 19 columns is as follows:
An error occurred when executing the SQL command: COPY
colleges2014_15( unitid, intsnm, city, stabbr, zip_clean,
control, latitude, longitude, tutionfee_in, tuitionfee_out,
pctpell, inc_pct_…ERROR: extra data after last expected column Where: COPY
colleges2014_15, line 2: «100654,Alabama A & M
University,Normal,AL,35762,35762,1,34.783368,-86.568502,9096,16596,0.7356,0.651…»
1 statement failed.Execution time: 0.03s
The full error message when trying to copy simply the first column only is:
An error occurred when executing the SQL command: COPY
colleges2014_15( unitid ) FROM
‘/Users/compose/Downloads/CollegeScorecard_Raw_Data
x/MERGED2014_15_cleaned.csv’ CSV HEADERERROR: extra data after last expected column Where: COPY
colleges2014_15, line 2: «100654,Alabama A & M
University,Normal,AL,35762,35762,1,34.783368,-86.568502,9096,16596,0.7356,0.651…»
1 statement failed.Execution time: 0.01s
Hugely appreciate any help.
I am working on a project where I need to create a new table, then import data from a CSV. I’ve read many similar questions («extra data after last expected column») and answers on StackOverflow, but I still haven’t found the culprit.
CREATE TABLE colleges2014_15 (
unitid integer,
intsnm text,
city text,
stabbr text,
zip_clean char,
control integer,
latitude float,
longitude float,
tutionfee_in float,
tuitionfee_out float,
pctpell float,
inc_pct_lo float,
dep_stat_pct_ind float,
dep_debt_mdn float,
ind_debt_mdn float,
pell_debt_mdn float,
ugds_men float,
ubds_women float,
locale integer,
PRIMARY KEY(unitid)
);
The table is created successfully with the 19 different columns. Then I go try to import the data into the new table.
COPY colleges2014_15(
unitid,
intsnm,
city,
stabbr,
zip_clean,
control,
latitude,
longitude,
tutionfee_in,
tuitionfee_out,
pctpell,
inc_pct_lo,
dep_stat_pct_ind,
dep_debt_mdn,
ind_debt_mdn,
pell_debt_mdn,
ugds_men,
ubds_women,
locale
)
FROM '/Users/compose/Downloads/CollegeScorecard_Raw_Data x/MERGED2014_15_cleaned.csv' CSV HEADER
;
And I get the error message. I’ve done the following in the CSV:
- Made sure it’s saved as UTF-8 CSV (working on a Mac)
- Already cleaned out all commas in every row
- Cleaned out all NULL values
- Confirmed that all the data types (integer, float, text, etc.) are correct
- I’ve tried to simply COPY only the first column,
unitid; it failed. I’ve tried importing only the second column (intsnm) and it failed with the same error.
The full error message when trying to COPY over all 19 columns is as follows:
An error occurred when executing the SQL command: COPY
colleges2014_15( unitid, intsnm, city, stabbr, zip_clean,
control, latitude, longitude, tutionfee_in, tuitionfee_out,
pctpell, inc_pct_…ERROR: extra data after last expected column Where: COPY
colleges2014_15, line 2: «100654,Alabama A & M
University,Normal,AL,35762,35762,1,34.783368,-86.568502,9096,16596,0.7356,0.651…»
1 statement failed.Execution time: 0.03s
The full error message when trying to copy simply the first column only is:
An error occurred when executing the SQL command: COPY
colleges2014_15( unitid ) FROM
‘/Users/compose/Downloads/CollegeScorecard_Raw_Data
x/MERGED2014_15_cleaned.csv’ CSV HEADERERROR: extra data after last expected column Where: COPY
colleges2014_15, line 2: «100654,Alabama A & M
University,Normal,AL,35762,35762,1,34.783368,-86.568502,9096,16596,0.7356,0.651…»
1 statement failed.Execution time: 0.01s
Hugely appreciate any help.