I have a database with a single column and create it like this
function populateDB(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS RESULT(result, UNIQUE(result))');
}
however, when I want to write objects into the table, I get the error:
could not execute statement (19 constraint failed)
The error only appears when I add the NOT NULL and PRIMARY KEY to the set-Up. Without it, it keeps writing duplicates in my database (I fill the database with data from a webservice on startup of a phonegap iOS application, so I want to catch duplicate rows on database level)
At first I had only "PRIMARY KEY" in it, and because the error says something about constraints, I was assuming the primary key has to be "NOT NULL", adding it to the code, I still got the same error.
how can I solve this. thanks in advance
edit: Maybe it´s important for you to know that I write stringyfied JSON Objects into the results column.
edit: I insert the object in this function. Basically I do it one by one:
this.save = function(){
db.transaction (function(transaction){
object = $.toJSON(self);
object = encodeURI(object);
transaction.executeSql('INSERT INTO RESULT (result) VALUES ("'+object+'")');
},
errorCB,
successCB
);
}
edit: I updated my set up table code. The error doesnt occur on every row, but the objects are actually unique.
"IF NOT EXISTS" is the catch here. You get constraint failed when you use conditions like "IF NOT EXISTS" or "REPLACE", "IGNORE" etc in SQLite queries.
Suppose, you're trying to create a table that already exists, then the constraint (here not creating the table again if it already exist) fails and hence the query fails (which you actually want - you dont want to duplicate the tables right?) and gives you the error constraint failed.
You may get a similar error on INSERT or REPLACE, INSERT or IGNORE, etc...
Related
Error message
The above image shows the error image whenever I tried to execute the sql command to get data table in VB .NET as shown below: (note: sqlstr and dttable has been declared before function headers, therefore no declaration here)
Public Function retrieveProducts() As DataTable
sqlstr = "SELECT * FROM products;"
dttable = MysqlClient.DataHandler.GetDataTable(sqlstr, conn, True)
If Not IsNothing(dttable) Then
Return dttable
End If
Return Nothing
End Function
Before you guys link the problem to any "duplicate" question, I want to inform that I had browsed a ton of answers from similar questions and none of them worked for me.
Here are the solutions I tried:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
I tried ? dttable.GetErrors(0).RowError on debug mode and it says "Referenced object has a value of 'Nothing'."
I also tried removing constraints of data table in my program (putting the remove function before the MysqlClient.DataHandler.GetDataTable function causes nothing to be returned)
Note:
The solution for dataset.enforceConstraints = false should be my last resort since my supervisor requested the program structure to revolve around MySqlClient data handler. If it's possible I wanted to resolve this without using data set.
As for the table itself, it has a foreign key constraint referencing to another table, the values in the table didnt violate any non-null and unique constraints. Besides that, other table with foreign key constraint too however, can be retrieved successfully. So I am confused with what is wrong.
DDL of the target table
I am working on a homework assignment and this is the question:
Write a script that attempts to insert a new division named “Guitars” into the Division table. If the
insert is successful, the script should display this message:
SUCCESS: Record was inserted.
If the update is unsuccessful, the script should display a message something like this:
FAILURE: Record was not inserted.
Error 2627: Violation of UNIQUE KEY constraint
'UQ__Division__5A98D48EAD30FDC4'. Cannot insert duplicate key in object
'dbo.Division'. The duplicate key value is (Guitars).
I honestly have no Idea where to start, just looking for some help. If you are going to give the full answer please explain a little if you can so I can actually learn. Thanks
I'm trying to make a foreign key. When I execute the query below, it returns blank with neither an explanation nor an error.
alter table MySQL."GrossHomeSales"
add constraint fk_zip_code
foreign key (nhs_prev_zip) references MySQL."Location" (zip_code);
You have not mentioned what your sql client is. If you are using psql, it does say ALTER TABLE when you make an alteration to a table. If instead you were using pgadmin 3, it would say something like
Query returned successfully with no result in 345 msec.
The reason that you are not seeing any output could be because this is really large table with several million rows, Then it could take a few minutes to create the index so don't expect instant output.
The other likely reason for not receiving any immediate response is because the table has been locked by another long running query.
Finally your question title says postgresql but your table has mysql in it's name?? (this is not related, just curious)
I would like to know is it possible to return a DB ERROR code from trigger, rather than Custom exception created with RAISE_APPLICATION_ERROR. I have some requirement where i need to return an DB ERROR code like 1 for Unique Constraint. I have a purpose to ask this, because for some reason with some hash based partition we are not creating unique constraints on table and rather have one trigher with which i want to return Unique constraint as an error code after checking if the record exists in DB.
You can use:
RAISE DUP_VAL_ON_INDEX;
Only in this case you can't pass any arguments to this error and you will get:
ORA-00001: unique constraint (.) violated
Is there a way to prevent sql from throwing an error when I try to save a record that already exists. I've got a composite key table for a many-to-many relationship that has only the two values, when I update a model from my application, it tries to save all records, the records that already exist throw an error Cannot insert duplicate key is there a way of having the database ignore these, or do I have to handle it in the application?
you are calling an INSERT and trying to add duplicated keys. This error is by design, and essential. The DB is throwing an exception for an exceptional and erroneous condition.
If you are, instead, trying to perform an "upsert" you may need to use a stored procedure or use the MERGE syntax.
If, instead, you don't want to UPDATE but to just ignore rows already in the table, then you need to simply add an exception to your INSERT statement... such as
....
WHERE
table.Key <> interting.key
Try something like this with your insert statement.
insert into foo (x,y)
select #x,#y
except
select x,y from foo
This will add a record to foo, ONLY if it is not already in the table.
You could try creating your index with the IGNORE_DUP_KEY option so that you only get a warning when you have duplicate keys rather than a true error.
The other option and possibly the better one is to use the MERGE statement rather than insert. The MERGE statement let's you do Inserts, Updates and Deletes all in one statement and sounds like it should work out well for what you are trying to do.
Last but not least, as you said fix it in your app and only insert the rows that need to be added.