Syntax error with upsert while using latest version - java

I am trying to execute the following query:
INSERT INTO `xguilds_relations` ( `id1`, `id2`, `dominance` ) VALUES ( ?, ?, ? )
ON CONFLICT DO UPDATE SET `dominance` = VALUES(`dominance`);
However, this results in giving me the following syntax error:
SQL error or missing database (near "UPDATE": syntax error)
I have been looking through Google and Stackoverflow for a while and all I found was that UPSERT is only supported since SQLite 3.24.0. However, I am using 3.30.1 and it's still not working.
What I would like to achieve is:
- Insert a new row into xguilds_relations with the provided id's (table contains a CHECK (id1 > id2) or something similar) and the provided dominance
- If a row with the provided id's already exists, update that row with the new dominance value

I don't think SQLite supports VALUES. Does this work?
INSERT INTO xguilds_relations ( id1, id2, dominance )
VALUES ( ?, ?, ? )
ON CONFLICT DO UPDATE SET dominance = excluded.dominance;
You may want to also include the columns that you conflict refers to.

UPSERT works when there is a violation of a UNIQUE constraint and not a CHECK constraint.
Is there a UNIQUE constraint for the combination of id1 and id2? I believe not.
So create it:
CREATE UNIQUE INDEX IF NOT EXISTS un_id1_id2 ON `xguilds_relations` (`id1`, `id2`);
Now write the statement like this:
INSERT INTO `xguilds_relations` ( `id1`, `id2`, `dominance` ) VALUES ( ?, ?, ? )
ON CONFLICT(id1, id2) DO UPDATE SET `dominance` = <value>;
See a simplified demo.

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);

UPDATE with LEFT JOIN not working with UCanAccess

I am trying to update the table row in MS Access from NetBeans. But I am getting the error -
net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: LEFT required: SET
I had tested the query directly in MS-Access, which is working perfectly. But when I use that same query in NetBeans it throwing the error.
Two tables are connected each other - category and Product tables.
Category ID (Primary Key, AutoIncrement) will be the foreign key in product table.
Now I want to update the details of product in Product table.
My Update Query :
ps_ins_new_prod = con.prepareStatement("UPDATE Inv_Category LEFT JOIN Inv_Product ON Inv_Category.Category_ID = Inv_Product.Category_ID SET Inv_Product.[Size] = ?, Inv_Product.Quantity = ?, Inv_Product.Item_No = ?, Inv_Product.Purchase_Price = ?, Inv_Product.Selling_Price = ?, Inv_Product.Category_ID = ? WHERE (((Inv_Product.Product_Name)=?) AND ((Inv_Product.Size)=?) AND ((Inv_Category.Category_Name)=?) AND ((Inv_Product.Quantity)=?) AND ((Inv_Product.Item_No)=?) AND ((Inv_Product.Purchase_Price)=?) AND ((Inv_Product.Selling_Price)=?) AND ((Inv_Product.Category_ID)=?))");
Internally Ucanaccess runs your query against a HSQLDB database which does not support LEFT OUTER JOINS in an UPDATE.
See this thread for a discussion and a possible workaround using the MERGE command.

Mixing Parameterized Query and Sub-query on Insert

I have a colleague who wants to attempt the following query:
INSERT INTO table (ColumnA, ColumnB, ColumnC)
VALUES (?, (SELECT Id FROM ColumnD WHERE x=y), ?)
Sybase complains about this as it does not seem to allow subqueries in the VALUES portion of the query. Does anyone know of a way around this problem?
How about:
INSERT INTO table (ColumnA, ColumnB, ColumnC)
SELECT
?,
Id,
?
FROM
TableD
WHERE
x = y
(Or similar)

Howto return ids on Inserts with Ibatis ( with RETURNING keyword )

I'm using iBatis/Java and Postgres 8.3.
When I do an insert in ibatis i need the id returned.
I use the following table for describing my question:
CREATE TABLE sometable ( id serial NOT NULL, somefield VARCHAR(10) );
The Sequence sometable_id_seq gets autogenerated by running the create statement.
At the moment i use the following sql map:
<insert id="insertValue" parameterClass="string" >
INSERT INTO sometable ( somefield ) VALUES ( #value# );
<selectKey keyProperty="id" resultClass="int">
SELECT last_value AS id FROM sometable_id_seq
</selectKey>
</insert>
It seems this is the ibatis way of retrieving the newly inserted id. Ibatis first runs a INSERT statement and afterwards it asks the sequence for the last id.
I have doubts that this will work with many concurrent inserts. ( discussed in this question )
I'd like to use the following statement with ibatis:
INSERT INTO sometable ( somefield ) VALUES ( #value# ) RETURNING id;
But when i try to use it within a <insert> sqlMap ibatis does not return the id. It seems to need the <selectKey> tag.
So here comes the question:
How can i use the above statement with ibatis?
The <selectKey> element is a child of the <insert> element and its content is executed before the main INSERT statement. You can use two approaches.
Fetch the key after you have inserted the record
This approach works depending on your driver. Threading can be a problem with this.
Fetching the key before inserting the record
This approach avoids threading problems but is more work. Example:
<insert id="insert">
<selectKey keyProperty="myId"
resultClass="int">
SELECT nextVal('my_id_seq')
</selectKey>
INSERT INTO my
(myId, foo, bar)
VALUES
(#myId#, #foo#, #bar#)
</insert>
On the Java side you can then do
Integer insertedId = (Integer) sqlMap.insert("insert", params)
This should give you the key selected from the my_id_seq sequence.
Here is simple example:
<statement id="addObject"
parameterClass="test.Object"
resultClass="int">
INSERT INTO objects(expression, meta, title,
usersid)
VALUES (#expression#, #meta#, #title#, #usersId#)
RETURNING id
</statement>
And in Java code:
Integer id = (Integer) executor.queryForObject("addObject", object);
object.setId(id);
This way more better than use :
It's simpler;
It have not requested to know sequence name (what usually hidden from postgresql developers).

Categories

Resources