In a registration software made with Qt4, I open an Access .mdb database, update it with the user-provided fields.
It has currently a table clients with six fields:
CustomerNumber, FullName, CNICNumber, ResidentialAddress, ResidentialPhoneNumber, MobileNumber
where CustomerNumber is primary key and a number, while all others are text. There are a few records present. But when another record with same CustomerNumberis tried to be inserted, there is an error:
QODBCResult::exec: Unable to execute
statement: "[Microsoft][ODBC Microsoft
Access Driver] The changes you
requested to the table were not
successful because they would create
duplicate values in the index, primary
key, or relationship. Change the data
in the field or fields that contain
duplicate data, remove the index, or
redefine the index to permit duplicate
entries and try again."
"[Microsoft][ODBC Microsoft Access
Driver] The changes you requested to
the table were not successful because
they would create duplicate values in
the index, primary key, or
relationship. Change the data in the
field or fields that contain duplicate
data, remove the index, or redefine
the index to permit duplicate entries
and try again." "QODBC3: Unable to
execute statement"
I then found the UPDATE query, but the following code gives another error:
query.exec("UPDATE clients"
"SET FullName='"+cname+"', CNICNumber='"+cnic+"', ResidentialAddress='"+caddress+"', ResidentialPhoneNumber='"+cphone+"', MobileNumber='"+cmobile+"'"
"WHERE CustomerNumber="+cnumber+";");
The variables cname, cninc, caddresss, cphone, cmobile, cnumber are strings with values. But the error with the above code is:
QODBCResult::exec: Unable to execute
statement: "[Microsoft][ODBC Driver
Manager] Function sequence error"
"[Microsoft][ODBC Driver Manager]
Function sequence error" "QODBC3:
Unable to execute statement"
What is the solution to this, i.e. how to insert a new record when the primary key is not present but update existing record with same primary key?
You are missing spaces. The actual command you are executing is equivalent to
query.exec("UPDATE clientsSET Fullname...
there is no such table as clientsSET.
Here is what you intended
query.exec("UPDATE clients"
" SET FullName='"+cname+"', CNICNumber='"+cnic+"', ResidentialAddress='"+caddress+"', ResidentialPhoneNumber='"+cphone+"', MobileNumber='"+cmobile+"'"
" WHERE CustomerNumber="+cnumber+";");
If these are user-input values you are vulnerable to SQL injection. You need to be careful to scrub all the string values (eg. replace all ' with '').
What is the solution to this, i.e. how
to insert a new record when the
primary key is not present but update
existing record with same primary key?
This is known informally as an UPSERT. See this answer that relates to Access.
query.exec("UPDATE clients"
...CNICNumber='"+cnic+"', ...
My guess would be that CNICNumber shouldn't have single quotes around it.
...CNICNumber="+cnic+", ...
But it's impossible to tell for sure without knowing your table structure.
Can you try with:
+ " SET FullName='"+cname+ ...
+ " WHERE CustomerNumber="+cnumber+";");
in the second and third row?
Related
I need help with this
I have an MS Access db form which will enable users edit details about a project and the new values entered will be saved to the db table when the save button is clicked I am using the sql UPDATE syntax to do this and my code is similar to below
Private Sub Save_Click()
ltemp = " UPDATE Table1 "
ltemp = ltemp & " SET ClientName = 'ANN' "
ltemp = ltemp & " WHERE ProjectID = 2333 "
CurrentDb.Execute (ltemp)
End Sub
with this code, nothing happened. The code would execute with no errors but the value on the table wouldnt change.
I tried the code
DoCmd.RunSQL " UPDATE Table1 SET ClientName = 'ANN' WHERE ProjectID = 2333"
with this i got a long error message which indicated that the records couldnt be updated due to key violation. The problem is that the field 'ClientName' is not the primary key, although it is linked (in a relationship) to the primary key of another table.
both codes work to update other fields except this one which is in a relationship with the primary key of another table.
Obviously there is no record in your 'client' table with the 'ANN' id, so it cannot be set as a valid value for the corresponding\foreign key field in your updated table.
currentDb.execute instruction will not return any error message (not like the 'DoCommand' one) because it's not supposed to, as long as the syntax is correct (see below). You could try to use the currentDb.RecordsAffected to check if any record was changed by your instruction. Check parameters available for the execute method for further details.
Access Help:
"In a Microsoft Jet workspace, if you provide a syntactically correct SQL statement and have the appropriate permissions, the Execute method won't fail — even if not a single row can be modified or deleted. Therefore, always use the dbFailOnError option when using the Execute method to run an update or delete query. This option generates a run-time error and rolls back all successful changes if any of the records affected are locked and can't be updated or deleted."
You are attempting to violate the referential integrity set up on your database.
As you've noted, there is another table, which will look something like this:
CREATE TABLE Client
(
ClientName VARCHAR(100),
... other client fields here
);
And there is a FOREIGN KEY setup between columns Table1.ClientName and Client.ClientName.
To avoid this, either:
INSERT a client with the name ANN into the other table
DROP the foreign key constraint on Table1.ClientName if you intend to violate the constraint (but note that joins may fail when the client is missing)
Change the design and start using surrogate keys, such as ClientID and referencing the Surrogate key in your other tables (instead of 'natural' keys like Client Name). This way, clients can get married, change their names etc and your database won't break :)
Trying to run
INSERT INTO BOOKING_EXTRAS (BOOKING_ID, EXTRAS_, EXTRAS_PRICE) VALUES ('1','Phone call: 1.80','1.8');
in Oracle SQL Developer. Ive had it running but when I close it, then reopen it I get this error:
Error starting at line 1 in command:
INSERT INTO BOOKING_EXTRAS (BOOKING_ID, EXTRAS_, EXTRAS_PRICE) VALUES ('1','Phone call: 1.80','1.8')
Error report:
SQL Error: ORA-00001: unique constraint (COURSEWORK_XE.BOOKING_EXTRAS_PK) violated
00001. 00000 - "unique constraint (%s.%s) violated"
*Cause: An UPDATE or INSERT statement attempted to insert a duplicate key.
For Trusted Oracle configured in DBMS MAC mode, you may see
this message if a duplicate entry exists at a different level.
*Action: Either remove the unique restriction or do not insert the key.
how would I fix this? Its happening to every table I run!
You need to either clear the tables or insert new information, a database doesn't want duplicate rows because that makes it impossible to find the correct rows later.
In addition, if that BOOKING_ID (currently serves as primary key if I guess right) doesn't actually mean something for you, you can set it as AUTO INCREMENT in your schema, then afterwards you don't need to insert a value for BOOKING_ID, the system will automatically find a value which is not duplicate for you. This might save you a lot effort.
INSERT INTO BOOKING_EXTRAS (EXTRAS_, EXTRAS_PRICE) VALUES ('Phone call: 1.80','1.8');
If your unique column is being populated by a sequence, check to make sure that your sequence has the same 'last value' as your highest-value unique column.
I just encountered a problem where the sequence had a 'last value in' that was much lower than the highest value in my unique column. The DBA ran a script to update the sequence to what the number should have been, and my error went away.
Now to find out why the sequence was so wrong...
I have access database called road.mdb.
Inside road.mdb, I have a linked SQL table and
the table name is student.
I can insert records using query design in MSAccess
But I cannot update nor Delete
when run delete query below, the error is: could not delete from specified table
delete from student where studentid=303;
and when I run update query below, the error is: Operation must use an updateable query
update student set Name='BOB' where studentid= 303;
I have full access to the sql database and I can run the query OK using sql management studio.
Is it impossible to delete and update using query design inside MSaccess??
The weird thing is I can insert new records using query design inside MSaccess
thank you
I SOLVED this by adding primary key to the SQL table and re linked the table to ACCESS
Thanks everyone...
In the case that you can't manipulated the table on SqlServer, you can get around the problem by telling Access which/s column/s are meant to be the primary key. This is done on the last step of creating a Linked table, the window title is "Select Unique Record Identifier".
You will find that the following steps will most likely solve your problem:
In SQL Server: set a primary key on the table you are working with and make sure the primary key is of type int, not bigint as Access will not properly deal with bigint data type.
In SQL Server: refresh the table.
In MS Access: re-link the table.
(You can easily check if 'things are OK' afterwards by adding a record to the SQL Server table and accessing it through the MS Access linked table. When all is OK you should not see #Deleted when viewing the data from MS Access side.)
Hope it helps ;-)
In my case, the linked table only had keys. I had to modify one of the keys to be a primary key and then I could truncate truncate the table via a DELETE table.* FROM table via access.
In my case the problem was a BIT column. I think the problem occurs when the the bit column contains a NULL value.
To resolve the issue, I either deleted the entire column, or set a default value.
I want to delete all rows from table in sql server 2000 but whenever I want to delete manually or with query it shows error. In help tab it shows ODBC error: <0s>.
My table contains some '0' values but its datatype is String. Is that's the reason for this
error.
code is:
stat2=conn.createStatement();
stat2.executeUpdate("Delete * from pat.dbo.PHPL");
"Key column information is insufficient or incorrect. Too many rows were affected by update" that's warning and when click help it shows: ODBC error: <0s>. An ODBC error has been generated. You might have deleted a record that has a foreign key value related to it, or you might have violated a check constraint. For details, refer to your ODBC documentation.
Use
Truncate Table PHPL
I think you have duplicate identities, check you are not allowing duplicates on this column.
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...