Ошибка вставки новой записи [РЕШЕНО]
Автор GOYa, 20 мая 2010, 11:14
0 Пользователи и 1 гость просматривают эту тему.
Помогите.
При вводе данных из формы выдает
«Ошибка вставки новой записи»
Прм повторном вводе
«Ошибка вставки новой записи»
Состояние SQL: 23000
Код ошибки: -104
Violation of unique constraint SYS_PK_47: duplicate value(s) for column(s) «ID» in statement [INSERT INTO «Таблица1» ( «ID»,»Test») VALUES ( ?,?)]
Но данные в таблицу вводятся.
[вложение удалено Администратором]
Очевидно, в поле ID вводятся повторяющиеся значения. Поскольку данное поле у Вас объявлено первичным ключом, его значения должны быть уникальными.
Насколько хватает моих знаний — ругается на то, что вводятся одинаковые значения в поле ID, которое должно быть уникальным, ибо первичный ключ.
Update: Упс, опередили 
А вообще, первичный ключ-ID лучше делать самозаполняющимся, т.е. выставить Автозначение в «Да».
A Matter of Life and Death
В том то и вопрос, что таблица изначально пустая, а вводится первая запись.
См. прикрепл. файл.
она не пустая.
Update: у Вас форма в режиме «только добавление», поэтому существующие записи не показываются.
[вложение удалено Администратором]
Цитата: Helen от 20 мая 2010, 11:58
она не пустая.Update: у Вас форма в режиме «только добавление», поэтому существующие записи не показываются.
Приношу свои извинения за кривизну рук. Но делал все по мануалу:
создал базу
в ней таблицу с двумя полями: ID- самозаполняющийся и name — текстовое поле
мастером прикрутил форму только для ввода данных
и когда ввожу запись в поле name выскакивает эрор из первого поста хотя данные в таблицу таки заносятся. 
[вложение удалено Администратором]
Цитата: GOYa от 20 мая 2010, 14:11и когда ввожу запись в поле name выскакивает эрор из первого поста
не могу воспроизвести. Расскажите пошагово, как вносятся данные в форме, начиная с открытия.
Цитата: GOYa от 20 мая 2010, 14:11и когда ввожу запись в поле name выскакивает эрор из первого поста хотя данные в таблицу таки заносятся.
Воспроизвёл. Что интересно — так когда форма создана только для внесения новых данных. Если форма позволяет просматривать и редактировать уже существующие данные, ошибки нет.
A Matter of Life and Death
1. Открыл файл
2. Вызвал форму tab1
3. В поле name ввёл данные
4. Нажал иконку «Следующая запись» на нанели инструментов Навигация формы
5. Ошибка.
A Matter of Life and Death
не могу 
ООо 3.2.1 RC1.
Самое интересное, что эта трабла с оигинальной Оо 3.2, а с Оо 3.1 от Nowell с той же самой базой проблем нет
Цитата: GOYa от 20 мая 2010, 14:59Самое интересное, что эта трабла с оигинальной Оо 3.2, а с Оо 3.1 от Nowell с той же самой базой проблем нет
Видимо, проблему закрыли в Go-OO раньше. Через неделю где-то выйдет 3.2.1 Communinty, проверим ещё разочек там.
A Matter of Life and Death
Цитата: Syzygy от 20 мая 2010, 16:07
Цитата: GOYa от 20 мая 2010, 14:59Самое интересное, что эта трабла с оигинальной Оо 3.2, а с Оо 3.1 от Nowell с той же самой базой проблем нет
Видимо, проблему закрыли в Go-OO раньше. Через неделю где-то выйдет 3.2.1 Communinty, проверим ещё разочек там.
Нет в Go-OO 3.2-13 этот баг есть. Нет в Оо 3.1 от Nowell. Но возможно его нет и в оригинале Оо 3.1
Свобода информации — свобода личности!
I know what the error means, and why it’s occurring, meaning this is not a duplicate of the many topics covering State 23000. I’m using PDO to insert a duplicate record into a table that has a compound PK. I did this on purpose, in order to automatically cancel the insertion of any duplicated records in to this specific table.
The error, SQLSTATE[23000]: Integrity constraint violation, is killing the script. Is there a way to set the warn level for this particular error, to literally tell it to shut up and carry on?
I don’t understand the purpose of having compound PKs if we can’t allow them to work for us?
I’m not very experienced with DB administration so you’ll have to forgive me if I come across a bit ‘it should work if I hit it with a hammer’.
Table Structure:
CREATE TABLE `cart` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(10) NOT NULL,
`itemid` int(10) NOT NULL,
UNIQUE KEY `id` (`id`),
UNIQUE KEY `unique_records` (`userid`,`itemid`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1
Note the compound PK called ‘unique records’.
so I have this table:
| id | userid | itemid |
| 1 | 175 | 12 |
And I execute this query:
$insertItem = $db->query("
INSERT INTO cart (userid, itemid)
VALUES (:userid, :itemid),
array("userid"=>"175", "itemid"=>"12")
");
Executing this query prompts this error: SQLSTATE[23000]: Integrity constraint violation.
I fully understand why I’m getting this error — I just don’t understand why it’s killing my submission? I thought it should just keep working ignoring the fact that a few records weren’t inserted because they were duplicates?
Advice appreciated!
I know what the error means, and why it’s occurring, meaning this is not a duplicate of the many topics covering State 23000. I’m using PDO to insert a duplicate record into a table that has a compound PK. I did this on purpose, in order to automatically cancel the insertion of any duplicated records in to this specific table.
The error, SQLSTATE[23000]: Integrity constraint violation, is killing the script. Is there a way to set the warn level for this particular error, to literally tell it to shut up and carry on?
I don’t understand the purpose of having compound PKs if we can’t allow them to work for us?
I’m not very experienced with DB administration so you’ll have to forgive me if I come across a bit ‘it should work if I hit it with a hammer’.
Table Structure:
CREATE TABLE `cart` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(10) NOT NULL,
`itemid` int(10) NOT NULL,
UNIQUE KEY `id` (`id`),
UNIQUE KEY `unique_records` (`userid`,`itemid`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1
Note the compound PK called ‘unique records’.
so I have this table:
| id | userid | itemid |
| 1 | 175 | 12 |
And I execute this query:
$insertItem = $db->query("
INSERT INTO cart (userid, itemid)
VALUES (:userid, :itemid),
array("userid"=>"175", "itemid"=>"12")
");
Executing this query prompts this error: SQLSTATE[23000]: Integrity constraint violation.
I fully understand why I’m getting this error — I just don’t understand why it’s killing my submission? I thought it should just keep working ignoring the fact that a few records weren’t inserted because they were duplicates?
Advice appreciated!
Have you used Set Term before and after this code?
All commands in Firebird must be terminated with a semi-colon. If you want to create a stored procedure you need to be able to distinguish between the terminating semi-colon from the semi-colons inside the stored procedure.
Something like this:
SET TERM ^ ;
CREATE PROCEDURE SP_NYANSAT(
FORNAVN VARCHAR(30),
EFTERNAVN VARCHAR(30),
ADRESSE VARCHAR(50),
POSTNUMMER CHAR(4),
TELEFONNUMMER CHAR(8),
EMAIL VARCHAR(50))
AS
DECLARE VARIABLE ID INTEGER;
BEGIN
ID = GEN_ID(GEN_ANSAT_ID,1);
INSERT INTO MYTABLE (ID, FORNAVN, EFTERNAVN, ADRESSE, POSTNUMMER, TELEFONNUMMER, EMAIL) VALUES (:ID, :FORNAVN, :EFTERNAVN, :ADRESSE, :POSTNUMMER, :TELEFONNUMMER, :EMAIL);
END
^
SET TERM ; ^
Please notice how the declaration of the stored procedure is terminated with ^, thus ending the statement. After the declaration you also restore the terminating semi-colon.
On a side note, I would recommend to copy firebird.msg to the location the error you get tells you so you can see what is really happening.
EDIT:
If you wish you can check this link. There you can find a lot of information regarding Firebird + IBExpress, including SET TERM (page 81).
EDIT 2:
Just tried at home with IBExperts + Firebird and I had no problem creating the stored procedure. My guess is you are trying to do one of the following things:
-
You have opened an SQL editor and are trying to compile the code directly. That will not work because IBExperts thinks you are trying to run DSQL sentences. Stored procedures are created with PSQL sentences.
-
You are trying to use the «New procedure» utility (check buttons in the upper right side of the main menu) and pasted the whole code into the editor. That will not work because in that editor you only have to put the body code. Stored procedure name is set in a field on the upper right side of the window you opened. Parameters and variables are introduced by using the «Insert Parameter/Variable» button on the left side above the code editor. The SET TERM sentences are created automatically by IBExperts. You can check the resulting code in the DDL tab.
HTH