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
Related
I Am new in stackoverflow and whats worst is I am new to Microsoft Access. My homework
Assume the Part table has been created, but there are no integrity constraints. Create the necessary integrity constraint to ensure that the only allowable values for the Class field are AP, HW, and SG. Ensure that the PartNum field is the primary key and that the PartNum field in the OrderLine table is a foreign key that must match the primary key of the Part table.
So I know how to create this by using Microsoft Access by going to the Validation Rule and add validation for AP, HW, and SG. However, I need to also create the query to show how this is done.
My code:
ALTER TABLE Parts
ADD CONSTRAINT classRule
CHECK IN Class(AP, HW, SG)
;
My textbook has an example which is similar to what I just wrote above. When I run this I get a Constraint error. What am I doing wrong? Also, the foreign key and primary key have already been made so I just need to write the sql query to display my result. Any help is appreciated!
The CHECK clause exists but it's not a particularly good idea to use it because it can create issues in you application.
That being said, your constraint should work but there are a couple things:
You should avoid the use of the word Class as a field name. It's not a reserved word per se, but it's a VBA reserved word and while Access let you create that field, you may encounter strange problems elsewhere later.
As Brian said, you need to use single quotes for string literals in your CHECK
You can't create CONTRAINT with CHECK from the SQL Query Editor in Access, you'll get errors on the CHECK part every time you try.
Instead you need to execute the DDL SQL from VBA: just open the VBA (Alt+F11) then type the following in the Immediate Window (Ctrl-G if you don't see it), then press ENTER:
CurrentProject.Connection.Execute "ALTER TABLE Parts ADD CONSTRAINT ClassRule CHECK (Class IN ('AP', 'HW', 'SG'));"
If you don't get an error, then the constraint was properly executed, otherwise, double check that the syntax is correct, field names, parenthesis are properly balanced, and that the Part table is not open.
You probably want:
ALTER TABLE Parts
ADD CONSTRAINT classRule
CHECK (class in ('AP', 'HW', 'SG'));
There is a space between CONSTRAINT and the name
Put conditions within the () after the CHECK keyword
Put literals within single quotes, as this is what differentiates field names from values
Edit
Although the above is valid syntax, from what I'm reading you may not be able to add a check constraint in Access via writing out the SQL, at least not in the SQL view of query designer.
You can add a check constraint by going to Design View for the table of interest, then on the row representing the column of interest, type the following on the line for "Validation Rule":
in ('AP', 'HW', 'SG')
http://www.databaseskill.com/1942875/
"Note The check constraint statement can only be executed through the Jet OLE DB provider and ADO; it will return an error message if used though the Access SQL View user interface."
Above quote is from the URL I just provided.
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 :)
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...
At work we have a table to hold settings which essentially contains the following columns:
PARAMNAME
VALUE
Most of the time new settings are added but on rare occasions, settings are removed. Unfortunately this means that any scripts which might have previously updated this value will continue to do so despite the fact that the update results in "0 rows updated" and leads to unexpected behaviour.
This situation was picked up recently by a regression test failure but only after much investigation into why the data in the system was different.
So my question is: Is there a way to generate an error condition when an update results in zero rows updated?
Here are some options I have thought of, but none of them are really all that desirable:
PL/SQL wrapper which notices the failed update and throws an exception.
Not ideal as it doesn't stop anyone/a script from manually doing an update.
A trigger on the table which throws an exception.
Goes against our current policy of phasing out triggers.
Requires updating trigger every time a setting is removed and maintaining a list of obsolete settings (if doing exclusion).
Might have problems with mutating table (if doing inclusion by querying what settings currently exist).
A PL/SQL wrapper seems like the best option to me. Triggers are a great thing to phase out, with the exception of generating sequences and inserting history records.
If you're concerned about someone manually updating rather than using the PL/SQL wrapper, just restrict the user role so that it does not have UPDATE privileges on the table but has EXECUTE privileges on the procedure.
Not really a solution but a method to organize things a bit:
Create a separate table with the parameter definitions and link to that table from the parameter value table. Make the reference to the parameter definition required (nulls not allowed).
Definition table PARAMS (ID, NAME)
Actual settings table PARAM_VALUES (PARAM_ID, VALUE)
(changing your table structure is also a very effective way to evoke errors in scripts that have not been updated...)
May be you can use MERGE statement
here is a link for it
http://www.oracle-developer.net/display.php?id=203
The merge statement allows you to combine insert and update in the same query, so in case the desired row does not exist you may insert a record in a buffer table to indicate the the row does not exist or else you can update the required record
Hope it helps
I am using RedBean ORM. In order to create the schema I used the standard redbean approach of inserting data so that Redbean would auto-fit the schema to suit my needs. I put this in a script which would basically be used to build the schema when i need to initialize my database.
The problem is that RedBean keeps a row or 2 in each table (the ones that I initially inserted to get redbean to build the schema).
If it were a normal database, to erase all rows i would just drop the schema and rebuild it, but in this case that's not possible since the initial rows would still exist.
Unfortunately there isn't too much Redbean Q/A out there. Anyone know how I would do this using the Redbean interface?
I have tried
$listOfTables = R::$writer->getTables();
foreach($listOfTables as $table)
{
R::wipe($table);
}
Of course this doesn't work though. (It doesn't TRUNCATE the tables in the correct order so I get an error about another table using this key as a foreign link. It simply iterates in ABC order)
Fatal error: Uncaught [42000] - SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint (`redbeandb`.`research`, CONSTRAINT `research_ibfk_1` FOREIGN KEY (`ownEducationHistory_id`) REFERENCES `redbeandb`.`educationhistory` (`id`)) thrown in C:\Users\Rod\nginx-1.0.12\html\rb.php on line 105
If someone has a (redbean api) solution, it would be much appreciated. And hopefully this question can be beneficial to building up more RedBean Q/A here on Stackoverflow.
Use
R::nuke();
Yes, it will drop all tables but since RedBeanPHP creates all tables on the fly this is not a problem.
I know this is an old post but I figured I'd help out someone finding this today. You can tell mysql to ignore foreign key checks if you don't care about data integrity (plan on wiping all related tables).
R::exec('SET FOREIGN_KEY_CHECKS = 0;');
$listOfTables = R::$writer->getTables();
foreach($listOfTables as $table)
{
R::wipe($table);
}
R::exec('SET FOREIGN_KEY_CHECKS = 1;');