I am working on an android project, basicli I have some x,y coordinates in my sqlite but when I add a new data I want to check the data and if there is same data overwrite it.
public void DBCreate(){
SQLITEDATABASE = openOrCreateDatabase("LatLongDatabase", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS myTable(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, mCurrentLocationLAT VARCHAR,mCurrentLocationLONG VARCHAR);");
}
public void SubmitData2SQLiteDB(){
SQLiteQuery = "INSERT INTO myTable (mCurrentLocationLAT, mCurrentLocationLONG) VALUES('"+mCurrentLocation.getLatitude()+"','"+mCurrentLocation.getLongitude()+"');";
SQLITEDATABASE.execSQL(SQLiteQuery);
Toast.makeText(CampaignActivity.this,"OK", Toast.LENGTH_LONG).show();
}
You need to use UPDATE query to update the row with PRIMARY_KEY if data exists or INSERT new row.
Since your table have a PRIMARY_KEY as id, you can check if row exists as below.
SELECT EXISTS(SELECT 1 FROM myTable WHERE id='ROW_ID');
If above query returns 1, then data exists, and you need to use UPDATE query as below, else use INSERT query.
UPDATE myTable SET mCurrentLocationLAT=value1, mCurrentLocationLONG=value2 WHERE id='ROW_ID';
SQLite has an INSERT OR REPLACE statement which can be shortened just to REPLACE which will insert a new row if it doesn't exist, or replace (delete then insert) a row if it does exist. Read the docs to learn about primary key constraints and how to handle them.
REPLACE INTO positions (title, min_salary)
VALUES
('Full Stack Developer', 140000);
Related
I need a bit of assistance in getting a connection between my two tables
These are the tables where "idPatient is the foreign key"
I fill the table "tanden" like this
public void addTandenToDatabase(int id, int fdi, String voorstelling, String toestand) {
String insertSql = "insert into tanden(id, fdi, voorstelling, toestand) values (:idVal, :fdiVal, :voorstellingVal, :toestandVal)";
try (Connection con = sql2o.open()) {
con.setRollbackOnException(false);
con.createQuery(insertSql)
.addParameter("idVal", id)
.addParameter("fdiVal", fdi)
.addParameter("voorstellingVal", voorstelling)
.addParameter("toestandVal", toestand)
.executeUpdate();
}
}
Everything is added nicely but the idPatient stays null
You should include idPatient in your insert if you want to set value to it. 'foreign key' doesnot mean that it will be set value automically.
You have to insert idPatient column value into tanden table by taking from patienten table.
Your id column in the tanden table should be set as primary key and autoincrement and you have to set the idPatient in your insert
insert into tanden(idPatient, fdi, voorstelling, toestand) values(:idVal,:fdiVal, :voorstellingVal, :toestandVal)";
(The idPatient you set in the child table already has to exist in the parent table
My javaFx application has many tables with editable table cells to populate data from sql database.I also want to make changes in database after data editing through table cells.According to this toturial "https://docs.oracle.com/javafx/2/ui_controls/table-view.htm"
I have created my editable table cell with the following code.
item_price_col.setCellValueFactory(
new PropertyValueFactory("price")
);
item_price_col.setCellFactory(TextFieldTableCell.forTableColumn());
item_price_col.setOnEditCommit(
new EventHandler<CellEditEvent<Item, String>>() {
#Override
public void handle(CellEditEvent<Item,String> t) {
String old_price=t.getOldValue();
((Item) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setPrice(t.getNewValue());
String new_price=t.getNewValue();
System.out.println("Old Price:"+old_price);
System.out.println("New Price:"+new_price);
}
}
);
But it doesn't make any changes in database after editing.So,I think have to write update Query inside of that handle method.But I can only know old value and new value. I can't make query statement like that "update item set price=new_price where price=old_price".If I update a single price of a item to new value,every items in my item table that have the same price with my edited item will make changes to new price value.Are there any ways to solve this problem?
Here is my item table structure.
item | CREATE TABLE `item` (
`code` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`price` varchar(50) NOT NULL,
`whole_sale_price` varchar(50) NOT NULL,
`orginal_price` varchar(50) DEFAULT NULL,
PRIMARY KEY (`code`),
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
Keep an id field to your item as it is given in the database.
If you have not primary or unique key in the database probably you made some architectural mistake. Anyway there is a row id specified in some database servers.
private int id; // id field for item object.
While updating include id as condition.
update sometable set price = item.getPrice() where id = item.getId();
I know sql is not well written but I hope you'll get it
And you don't have to show value of id field in your table grid.
This technique is used in most systems
EDITED 2015.12.18
You have code column in the table. Retrieve by jdbc into your item object's id field.
There is an example
http://www.tutorialspoint.com/jdbc/jdbc-update-records.htm
I'm using java and I want to insert to mysql database a data if not exist, Also I want to update that data if exist. but I couldn't find mysql command for this.
I found this code for Insert but this is not what I want
INSERT INTO contacts
(contact_id, contact_name)
SELECT supplier_id, supplier_name
FROM suppliers
WHERE EXISTS (SELECT *
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);
For update, I found this code. but this is not what I want.
UPDATE suppliers
SET supplier_name = (SELECT customers.customer_name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT *
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);
What I want to do is something like this
UPDATE student SET student_score = 20 where student_id = 1 WHERE EXIST ( select * from student where student_id = 1;
You can use:
insert into table_name (id, name, firstname) values(1, "Sessi", "Brahim") on duplicate key update name=values(name), firstname=values(firstname)
Adapt it to your query.
I have a webapp that I'm trying to set up an SQLite database with. At this point, I have it very simple to build a foundation. At this point there are only two tables. One table uses a foreign key constraint to point to the other table. The problem I am having is when I try to insert data, I always receive the error Error processing SQL: could not execute statement due to a constraint failure (19 constraint failed) -- Code: 6. Code 6, apparently, means the table is locked. How can it be locked if I can successfully insert values into it? Confused...
My code...
I set up the tables with this:
// Create a system table, if it doesn't exist
db.transaction(function(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS system(systemID TEXT PRIMARY KEY, numZones INT NULL, numHeads INT NULL)', [],nullHandler,errorHandler);
},errorHandler, successCallBack);
// Create a work order table, if it doesn't exist
db.transaction(function(tx){
tx.executeSql('CREATE TABLE IF NOT EXISTS wo(woID_id TEXT PRIMARY KEY, woType TEXT NOT NULL, systemID_fk TEXT NOT NULL, FOREIGN KEY (systemID_fk) REFERENCES system(systemID))', [],nullHandler,errorHandler);
},errorHandler, successCallBack);
Presumably now I will have two tables, one having a field that points to the other table. I am pulling in a JSon feed, parsing it, and trying to put it into these two tables. Here's the code for that parsing:
function GetSystems(){
// First we see if there are credentials stored. If not, we don't try to retrieve the work orders.
db.transaction(function(transaction){
transaction.executeSql('SELECT * FROM Creds;',[], function(transaction, result) {
// If the user hasn't entered their creds yet, we create a new record, otherwise update the current one.
if(result.rows.length != 0){
var row;
db.transaction(function(transaction){
transaction.executeSql('SELECT * FROM Creds where id=1;',[],function(transaction, result) {
$.getJSON(baseURL + "get-wos/?callback=?", { username:result.rows.item(0).username, password:result.rows.item(0).password }, function(data) {
$.each(data, function(i, obj) {
db.transaction(function(transaction){
transaction.executeSql('INSERT INTO system(systemID, numZones, numHeads) VALUES (?, null, null)', [obj.systemID], nullHandler, errorHandler);
transaction.executeSql('INSERT INTO wo (woID, woType, systemID_fk) ' +
'VALUES ((SELECT systemID FROM system WHERE systemID = ' + obj.systemID + '), ?, ?)',
[obj.woID, obj.woType], nullHandler, errorHandler);
})
});
});
});
});
}
});
});
}
When I run the above code, the systems are loaded properly but the wos are not. My research into this issue tells me that I might be having a few issues. One suggestion is that there may already be data in the table. I fixed that by having a drop tables function to clear out the database entirely (I use Chrome dev tools to investigate the db).
So really, I'm not sure what I'm doing wrong. Is my syntax incorrect for inserting a foreign key constraint?
Solved
I stumbled upon this thread and #havexz mentioned the variable in the insertion didn't have quotes around it. I looked at mine and it had the same problem. Here's my edited insert to add a record with a foreign key. Notice the systemID='" instead of the original which was simply systemID=". I was missing the single quotes around my variable.
db.transaction(function(transaction){
transaction.executeSql("INSERT INTO wo (woID, woType, systemID_fk) " +
"VALUES (?, ?, (SELECT systemID FROM system WHERE systemID='" + obj.systemID + "'))", [obj.woID, obj.woType], nullHandler, errorHandler);
});
Is the order of the parameters correct for the INSERT wo? It looks like you're putting the systemID into the woID field rather than systemID_fk which has the constraint. Should it be:
transaction.executeSql('INSERT INTO wo (woID, woType, systemID_fk) ' +
'VALUES (?, ?, (SELECT systemID FROM system WHERE systemID = ' + obj.systemID + '))',
[obj.woID, obj.woType], nullHandler, errorHandler);
I have an Android SQLite Database and I inserted some rows. After I deleted these rows the ID column continues from the last ID and I would like to restart the counting from 1.
Inside your .db file there's an table called sqlite_sequence
Each row has two columns 'name' which is the name of the table 'seq' a integer indicating the current last value at this table
You can update it to 0
But beware if your table use this id as the unique identifier.
Take a look at this answer: SQLite Reset Primary Key Field
Try:
delete from sqlite_sequence where name='your_table';
If you want to reset every RowId via content provider try this
rowCounter=1;do {
rowId = cursor.getInt(0);
ContentValues values;
values = new ContentValues();
values.put(Table_Health.COLUMN_ID,
rowCounter);
updateData2DB(context, values, rowId);
rowCounter++;
while (cursor.moveToNext());
public static void updateData2DB(Context context, ContentValues values, int rowId) {
Uri uri;
uri = Uri.parseContentProvider.CONTENT_URI_HEALTH + "/" + rowId);
context.getContentResolver().update(uri, values, null, null);
}