get Id of the rows which were updated by query - java

I want to get the primary key column value for the rows which were affected by query in Java. I am using MySql DB. Suppose query is like,
update user set pincode = 390023 where area like '%ABC Road%'
Then in java, I want the ids of each row (Primary key of each row) updated. Something that can be possible with Statement object in Java may be.

Select the rows just before you update them.
Use select id from user where area like '%ABC Road%'.
Remember to enclose those two operations in transaction to avoid row changes between those two.

SELECT id FROM user WHERE area LIKE '%ABC Road%';
or alternative way:
SET #ids = NULL;
UPDATE user
SET pincode = 390023
WHERE area LIKE '%ABC Road%'
AND (SELECT #ids := CONCAT_WS(',', id, #ids));
SELECT #ids;

Related

Insert into SQLite database if not exist in Java [duplicate]

I have an SQLite database. I am trying to insert values (users_id, lessoninfo_id) in table bookmarks, only if both do not exist before in a row.
INSERT INTO bookmarks(users_id,lessoninfo_id)
VALUES(
(SELECT _id FROM Users WHERE User='"+$('#user_lesson').html()+"'),
(SELECT _id FROM lessoninfo
WHERE Lesson="+lesson_no+" AND cast(starttime AS int)="+Math.floor(result_set.rows.item(markerCount-1).starttime)+")
WHERE NOT EXISTS (
SELECT users_id,lessoninfo_id from bookmarks
WHERE users_id=(SELECT _id FROM Users
WHERE User='"+$('#user_lesson').html()+"') AND lessoninfo_id=(
SELECT _id FROM lessoninfo
WHERE Lesson="+lesson_no+")))
This gives an error saying:
db error near where syntax.
If you never want to have duplicates, you should declare this as a table constraint:
CREATE TABLE bookmarks(
users_id INTEGER,
lessoninfo_id INTEGER,
UNIQUE(users_id, lessoninfo_id)
);
(A primary key over both columns would have the same effect.)
It is then possible to tell the database that you want to silently ignore records that would violate such a constraint:
INSERT OR IGNORE INTO bookmarks(users_id, lessoninfo_id) VALUES(123, 456)
If you have a table called memos that has two columns id and text you should be able to do like this:
INSERT INTO memos(id,text)
SELECT 5, 'text to insert'
WHERE NOT EXISTS(SELECT 1 FROM memos WHERE id = 5 AND text = 'text to insert');
If a record already contains a row where text is equal to 'text to insert' and id is equal to 5, then the insert operation will be ignored.
I don't know if this will work for your particular query, but perhaps it give you a hint on how to proceed.
I would advice that you instead design your table so that no duplicates are allowed as explained in #CLs answer below.
For a unique column, use this:
INSERT OR REPLACE INTO tableName (...) values(...);
For more information, see: sqlite.org/lang_insert
insert into bookmarks (users_id, lessoninfo_id)
select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;
This is the fastest way.
For some other SQL engines, you can use a Dummy table containing 1 record.
e.g:
select 1, 167 from ONE_RECORD_DUMMY_TABLE

Merge and When Matched query giving an error sql server

I have a query which I am trying to test. The query should update the data if it finds data in the table with existing primary key. If it doesn't then insert into the table.
The Primary key is of type int and in the properties I can see Identity is set to "True" which I assume it means that it will automatically set the new id for the primary if it is inserted.
MERGE INTO Test_table t
USING (SELECT 461232 ID,'Test1-data' Fascia FROM Test_table) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE SET t.Fascia = s.Fascia
WHEN NOT MATCHED THEN
INSERT (Fascia)
VALUES (s.Fascia);
The issue here is this query doesn't work and it never inserts the data or updates. Also, query gets compiled and I don't get any compilation error
Also the reason I want this query is to work because then I will use Java prepared statement to query the database so I am assuming I can do
SELECT ? ID,? Fascia FROM Test_table
So that I can pass the values with set methods in java.
Please let me know if there is something wrong in my query.
You are selecting from the target table as your source.
You either need to remove your FROM Test_table or have at least 1 row in Test_table prior to your merge.
rextester demo: http://rextester.com/XROJD28508
MERGE INTO Test_table t
USING (SELECT 461232 ID,'Test1-data' Fascia --FROM Test_table
) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE SET t.Fascia = s.Fascia
WHEN NOT MATCHED THEN
INSERT (Fascia)
VALUES (s.Fascia);

how get next autonumber from one column jdbc database?

I am using an access mdb file as my database . Inside the table in my database I use id as autonumber. Now. I wanted to know how can i get the next generated auto number field in access database to put in java JTextField!
To get next number you can insert a "blank" row and use the number that was generated for it.
If your insert statement is stmt:
int nextKey = 0;
ResultSet keys = stmt.getGeneratedKeys();
if (keys.next())
{
nextKey = keys.getInt(1);
}
See statement.getGeneratedKeys()
Alternatively you could generate new id number with
SELECT MAX(id)+1 FROM yourTable
though this doesn't guarantee that the number will stay unused (by some other query) before you do anything with it.

Multiple operation in same sql

I have a table with columns RECID,regionID, areaID ,UserID ,AppNo, NextAppNo(Accepts null)
and data is as follows (NextApp is not null in the first row only):
1,102,Ar-1,xyz,1,1
2,102,Ar-1,qwe,2
3,102,Ar-1,fgh,3
4,102,Ar-1,yuyi,4
1) Add a record
Now I want to add another record:
First I get the max number of APPID where areaID = Ar-1 and regionID =102 (Java)
Then, if max appNo is 0, add nextappNo, otherwise do nothing
Then insert into db
Is it possible to do this in one query?
2) Delete a record
In another query i want to delete the first record:
First I select data where areaID = 'Ar-1' and regionID =102
Then in a loop (Java) I check if Recid is the same id I want to delete
From there onward I update the the column approver and also, if the record which we are going to delete has approverNO = 1, then also update the next approver to one of the next record
Then delete the record from table.
You can use sql procedure to do it. It will be easier when you execute that single procedure with any type of operation such as insert,delete,update, etc.,

Deleting rows in linked MySQL tables and decrementing count in another table

I am trying to create (java-based) messaging webapp. The messages are stored using MySQL using three tables:
'messages': has two columns, an id primary key ('idmessage') and the message ('message').
'tags': The user also inputs a tag associated with their message. This has two columns - the tag (which is also a primary key) and a count ('count').
'message_tag_link': Since there is a many-to-one relationship between messages and tags I have a third link table. This has two columns, both foreign keys to the messages ('fk_idmessage') and tags tables’ ids ('fk_tag').
Inserting messages into the database works fine. I use these following lines in Java:
pst1 = connection.prepareStatement("INSERT INTO messages(message) VALUES (?)");
pst2 = connection.prepareStatement("INSERT INTO tags(tag,count) VALUES (?,1) ON DUPLICATE KEY UPDATE count = count + 1");
pst3 = connection.prepareStatement("INSERT INTO message_tag_link(fk_idmessage,fk_tag) VALUES (? , ?)");
As can be seen ‘count’ increments in pst2 every time a duplicate tag entry is made.
I am trying to work out how to fully delete a message. I have the on delete cascade description on my foreign keys in my link table’s columns but am not sure what to do next. For a given 'messageid' I need to:
Delete a row in 'messages' table
Delete the associated row in the 'message_tag_link' table
Decrement the count value in the 'tags' table when a message deletion is successful, or delete this row entirely if count becomes zero.
Is it possible to do all this within MySQL using a Java PreparedStatement? Any pointers much appreciated. I am a total MySQL novice, so please be kind!
These queries should do what you need. ? in each query should be the message id that is to be deleted
//Update count
UPDATE tags SET `count` = `count` - 1 WHERE tag_id IN (SELECT fk_tag FROM message_tag_link WHERE fk_idMessage = ?);
//Remove link
DELETE FROM message_tag_link WHERE fk_idmessage = ?;
DELETE FROM messages WHERE id = ?;
//Remove unused tags
DELETE FROM tags WHERE `count` = 0;
As you've found out however maintaining a count can be annoying. Better is to use the link itself.
SELECT COUNT(fk_idmessage) AS msgcount FROM message_tag_link WHERE fk_tag = ?;
Also you can add a CASCADE so that when messages are deleted the tag link gets deleted too (see here). Be careful with this behavior however).
This solution still leaves tags with no messages but you can remove these using the query:
DELETE FROM tags t WHERE NOT EXISTS (SELECT 1 FROM nessage_tag_link WHERE t.tag_id = fk_tag)

Categories

Resources