So my MySQL database is behaving a little bit wierd. This is my table:
Name shares id price indvprc
cat 2 4 81 0
goog 4 4 20 20
fb 4 9 20 20
I’m getting this #1062 error when I try to insert into the table. So I looked into it further and realized that when I try to insert values into the table, in which the name and shares values are the same, it will return the #1062 error. For example, If i inserted:
fb 4 6 20 20
It would return an error. But if i changed the shares number to 6, it would run fine. Is it because of one of my columns that could be unique, or is it just something with mysql?
asked Jul 24, 2012 at 20:05
5
You need to remove shares
as your PRIMARY KEY
OR UNIQUE_KEY
answered Jul 24, 2012 at 20:12
mlishnmlishn
1,67914 silver badges19 bronze badges
1
Use SHOW CREATE TABLE your-table-name
to see what column is your primary key.
answered Jul 24, 2012 at 20:10
Majid FouladpourMajid Fouladpour
29.2k20 gold badges76 silver badges127 bronze badges
2
- Make sure
PRIMARY KEY
was selectedAUTO_INCREMENT
. - Just enable Auto increment by :
ALTER TABLE [table name] AUTO_INCREMENT = 1
- When you execute the insert command you have to skip this key.
chw21
7,9151 gold badge16 silver badges31 bronze badges
answered Feb 4, 2016 at 2:34
I solved it by changing the «lock» property from «shared» to «exclusive»:
ALTER TABLE `table`
CHANGE COLUMN `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '' , LOCK = EXCLUSIVE;
davejal
6,00910 gold badges39 silver badges82 bronze badges
answered Dec 9, 2015 at 2:19
What is the exact error message? #1062 means duplicate entry violating a primary key constraint for a column — which boils down to the point that you cannot have two of the same values in the column. The error message should tell you which of your columns is constrained, I’m guessing «shares».
answered Jul 24, 2012 at 20:11
ChrisChris
3221 silver badge3 bronze badges
Probably this is not the best of solution but doing the following will solve the problem
Step 1: Take a database dump using the following command
mysqldump -u root -p databaseName > databaseName.db
find the line
ENGINE=InnoDB AUTO_INCREMENT="*****" DEFAULT CHARSET=utf8;
Step 2: Change *******
to max id of your mysql table id. Save this value.
Step 3: again use
mysql -u root -p databaseName < databaseName.db
In my case i got this error when i added a manual entry to use to enter data into some other table. some how we have to set the value AUTO_INCREMENT
to max id using mysql command
FastFarm
4091 gold badge6 silver badges21 bronze badges
answered Apr 15, 2013 at 10:15
KshitizKshitiz
2,6731 gold badge18 silver badges24 bronze badges
1
Repair the database by your domain provider cpanel.
Or see if you didnt merged something in the phpMyAdmin
answered Apr 14, 2017 at 20:03
The DB I was importing had a conflict during the import due to the presence of a column both autoincrement and primary key.
The problem was that in the .sql file the table was chopped into multiple «INSERT INTO» and during the import these queries were executed all together.
MY SOLUTION was to deselect the «Run multiple queries in each execution» on Navicat and it worked perfectly
answered Oct 30, 2020 at 9:01
ivorotoivoroto
90512 silver badges12 bronze badges
Do not mix SQLAlchemy commands with Python’s Try-Except. SQL will keep trying regardless, and the error will only show later in your program flow.
answered Mar 2 at 18:26
Al MartinsAl Martins
4135 silver badges13 bronze badges
I had this error from mySQL using DataNucleus and a database created with UTF8 — the error was being caused by this annotation for a primary key:
@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDSTRING)
protected String id;
dropping the table and regenerating it with this fixed it.
@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDHEX)
protected String id;
answered Jun 3, 2017 at 19:50
bsautnerbsautner
4,4091 gold badge35 silver badges49 bronze badges
2
So my MySQL database is behaving a little bit wierd. This is my table:
Name shares id price indvprc
cat 2 4 81 0
goog 4 4 20 20
fb 4 9 20 20
I’m getting this #1062 error when I try to insert into the table. So I looked into it further and realized that when I try to insert values into the table, in which the name and shares values are the same, it will return the #1062 error. For example, If i inserted:
fb 4 6 20 20
It would return an error. But if i changed the shares number to 6, it would run fine. Is it because of one of my columns that could be unique, or is it just something with mysql?
asked Jul 24, 2012 at 20:05
5
You need to remove shares
as your PRIMARY KEY
OR UNIQUE_KEY
answered Jul 24, 2012 at 20:12
mlishnmlishn
1,67914 silver badges19 bronze badges
1
Use SHOW CREATE TABLE your-table-name
to see what column is your primary key.
answered Jul 24, 2012 at 20:10
Majid FouladpourMajid Fouladpour
29.2k20 gold badges76 silver badges127 bronze badges
2
- Make sure
PRIMARY KEY
was selectedAUTO_INCREMENT
. - Just enable Auto increment by :
ALTER TABLE [table name] AUTO_INCREMENT = 1
- When you execute the insert command you have to skip this key.
chw21
7,9151 gold badge16 silver badges31 bronze badges
answered Feb 4, 2016 at 2:34
I solved it by changing the «lock» property from «shared» to «exclusive»:
ALTER TABLE `table`
CHANGE COLUMN `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '' , LOCK = EXCLUSIVE;
davejal
6,00910 gold badges39 silver badges82 bronze badges
answered Dec 9, 2015 at 2:19
What is the exact error message? #1062 means duplicate entry violating a primary key constraint for a column — which boils down to the point that you cannot have two of the same values in the column. The error message should tell you which of your columns is constrained, I’m guessing «shares».
answered Jul 24, 2012 at 20:11
ChrisChris
3221 silver badge3 bronze badges
Probably this is not the best of solution but doing the following will solve the problem
Step 1: Take a database dump using the following command
mysqldump -u root -p databaseName > databaseName.db
find the line
ENGINE=InnoDB AUTO_INCREMENT="*****" DEFAULT CHARSET=utf8;
Step 2: Change *******
to max id of your mysql table id. Save this value.
Step 3: again use
mysql -u root -p databaseName < databaseName.db
In my case i got this error when i added a manual entry to use to enter data into some other table. some how we have to set the value AUTO_INCREMENT
to max id using mysql command
FastFarm
4091 gold badge6 silver badges21 bronze badges
answered Apr 15, 2013 at 10:15
KshitizKshitiz
2,6731 gold badge18 silver badges24 bronze badges
1
Repair the database by your domain provider cpanel.
Or see if you didnt merged something in the phpMyAdmin
answered Apr 14, 2017 at 20:03
The DB I was importing had a conflict during the import due to the presence of a column both autoincrement and primary key.
The problem was that in the .sql file the table was chopped into multiple «INSERT INTO» and during the import these queries were executed all together.
MY SOLUTION was to deselect the «Run multiple queries in each execution» on Navicat and it worked perfectly
answered Oct 30, 2020 at 9:01
ivorotoivoroto
90512 silver badges12 bronze badges
Do not mix SQLAlchemy commands with Python’s Try-Except. SQL will keep trying regardless, and the error will only show later in your program flow.
answered Mar 2 at 18:26
Al MartinsAl Martins
4135 silver badges13 bronze badges
I had this error from mySQL using DataNucleus and a database created with UTF8 — the error was being caused by this annotation for a primary key:
@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDSTRING)
protected String id;
dropping the table and regenerating it with this fixed it.
@PrimaryKey
@Unique
@Persistent(valueStrategy = IdGeneratorStrategy.UUIDHEX)
protected String id;
answered Jun 3, 2017 at 19:50
bsautnerbsautner
4,4091 gold badge35 silver badges49 bronze badges
2
Ошибка
SQL запрос:INSERT INTO `wp_commentmeta` (`meta_id`, `comment_id`, `meta_key`, `meta_value`) VALUES
(1, 2, ‘rating’, ‘5’),
(2, 2, ‘verified’, ‘0’),
(3, 1, ‘_wp_trash_meta_status’, ‘1’),
(4, 1, ‘_wp_trash_meta_time’, ‘1464693386’),
(5, 3, ‘rating’, ‘1’),
(6, 3, ‘verified’, ‘0’)
Ответ MySQL: Документация
#1062 — Дублирующаяся запись ‘1’ по ключу ‘PRIMARY’
при загрузке в базу таблицы пробовали в zip тоже самое
Похожие вопросы
Ошибка при обновлении 1С-Битрикс (php 7 на MySQL Query Error?
С чем может быть связана следующая ошибка, и каким образом она решается. Текст ошибки, появляется на странице обновления CMS, а также модулей (при попытке загрузки и установки обновления).MySQL Query Error: delete o1 FROM b_user_access_check o1, b_user_access_check…
Паркуется домен при установке вп
Добрый день, подскажите почему паркуется домен при установке вордпреса на сайт? Мои действия:
1) создание бд, выставление прав к бд
2) установка вп
3) привязка домена
При переходе по ссылке, выдается страница парковки таймвеб
Подключение к базе данных через c#
Никто не сталкивался с проблемами подключения к базе данных msql на хостинге через c#?
Пробую, не получается!
буду очень рад любой вашей помощи!
На днях я переносил один из своих сайтов на новый хостинг и столкнулся с проблемой. Подробно о том, как перенести сайт на другой хостинг я расскажу в одной из следующих статей, а пока расскажу о самой проблеме и ее решении.
Файлы сайта я скопировал быстро, сделал экспорт базы данных со старого хостинга, но при попытке импортировать таблицы в базу на новом хостинге возникла ошибка в My SQL вот такого вида:
Ошибка
SQL-запрос:
— — Дамп данных таблицы `rich_blc_instances` — INSERT INTO `rich_blc_instances` (`instance_id`, `link_id`, `container_id`, `container_type`, `link_text`, `parser_type`, `container_field`, `link_context`, `raw_url`) VALUES (1, 1, 1, ‘blogroll’, ‘Документация’, ‘url_field’, ‘link_url’, », ‘http://codex.wordpress.org/Заглавная_страница’), (2, 2, 2, ‘blogroll’, ‘Блог WordPress’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/news/’), (3, 3, 3, ‘blogroll’, ‘Форумы поддержки’, ‘url_field’, ‘link_url’, », ‘http://ru.forums.wordpress.org/’), (4, 4, 4, ‘blogroll’, ‘Плагины’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/extend/plugins/’), (5, 5, 5, ‘blogroll’, ‘Темы’, ‘url_field’, ‘link_url’, », ‘http://wordpress.org/extend/themes/’), (6, 6, 6, ‘blogroll’, ‘Обратная связь’, ‘url_field’, ‘link_url’, », ‘http://ru.forums.wordpress.org/forum/20’), (7, 7, 7, ‘blogroll’, ‘Планета WordPr[…]
Ответ MySQL:
#1062 — Duplicate entry ‘1’ for key ‘PRIMARY’
Так как в базах данных я полный чайник, пришлось копаться в интернете в поисках решения. На форумах довольно много записей от людей с подобной проблемой, но нигде нет четкого ответа – сделай вот так и так.
В общих чертах я проблему понял, но вот как ее решить было неясно. На всех форумах, где встречалось описание подобной ошибки, люди писали, что она возникает при попытке добавить записи из одной базы данных в уже существующую другую.
Но я импортировал базу данных в пустые таблицы, более того, таблицы создавались в процессе импорта.
Решил проблему с ошибкой «#1062 — Duplicate entry ‘1’ for key ‘PRIMARY’» следующим образом:
Заменил в таблицах базы данных команду INSERT INTO на REPLACE INTO. В тексте ошибки, который я привел выше вы можете посмотреть в каком месте таблицы располагаются эти слова (выделил жирным).
По умолчанию, с помощью директивы insert база пыталась вставить значения в таблицу, но почему-то, находила дублированный key ‘PRIMARY’ и не могла вставить данные (как она их находила, я так и не разобрался). Директива replace заставила базу заменять данные при совпадении значений, не обращая внимания на прошлые записи.
Заменить эту директиву можно открыв сам файл базы данных с помощью текстового редактора – эта команда стоит перед блоком каждой таблицы. Открываете базу данных в текстовом редакторе, например, Akelpad и меняете все команды INSERT INTO на REPLACE INTO.
В моем же случае, получилось сделать проще – я по новой сделал экспорт таблицы на старом хостинге и в настройках экспорта установил этот самый REPLACE вместо INSERT.
- Подробности
- Категория: oscommerse
- Просмотров: 52588
Ошибка вида #1062 — Duplicate entry ‘1’ for key ‘PRIMARY’, может возникать при переносе на другой хостинг, у меня возникла, когда я переносил сайт на oscommerse…будем решать ее в этой статье…
Duplicate entry ‘1’ for key ‘PRIMARY’ — то есть вы пытаетесь создать то, что уже создано(в phpmyadmin). Обычно такая ошибка возникает, когда вы поверх уже установленной базы (БД) движка, пытаетесь сверху накинуть примерно такую же базу, но таблицы к примеру уже такие были созданы и поэтому вылазит такая ошибка.
Открываем файл БД в программе notepad++ и меняем INSERT INTO на REPLACE INTO. Теперь мы не будем создавать то, что уже есть, а будем перезаписывать. Теперь заливаем еще раз эту БД и ошибка должна исчезнуть.