How to update a column value in Cassandra Using CQL? - java

I have created a keyspace with two column fields. One is Id and another one is name. I have inserted records in that keyspace. I want to update the name filed of a particular id.
I have used the following CQL query
UPDATE keyspaceName/columnFalmilyName SET name='name' WHERE id = 'id'
While Executing this query it throws the Exception of
InvalidRequestException(why:line 1:56 mismatched input 'id' expecting K_KEY)...
If the query framed is wrong means, how to update the record using CQL?

Inserts and updates require specifying the row key, whereas you seem to be trying to use a column name. What key have you used when inserting new id,name pairs?
Refer to the CQL documentation on [http://cassandra.apache.org/doc/cql3/CQL.html][1]
<update-stmt> ::= UPDATE <tablename>
( USING <option> ( AND <option> )* )?
SET <assignment> ( ',' <assignment> )*
WHERE <where-clause>
The UPDATE statement writes one or more columns for a given row in a table. The
<where-clause> is used to select the row to update and must include all columns
composing the PRIMARY KEY. Other columns values are specified through <assignment>
after the SET keyword.
You need to take a look at your ColumnFamily definition and see what your primary key is.

Have you tried:
UPDATE keyspaceName/columnFalmilyName SET name='name' WHERE id = (without '')

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 to parse JSON Array to update record in postgreSQL

I have a Table name called employee_Details with Columns
EMP_ID NAME VECH_NO SALARY
1 A 1234 100
2 B 12345 200
I Construct JSON array using Java. with structure
{["EMP_ID":1,"NAME":Y,"VECH_NO":4587,"SALARY":1500],["EMP_ID":3,"NAME":Z,"VECH_NO":4007,"SALARY":1800]}
I need to update full record where EMP_ID exists on table else insert as new record. There is any in build function available in postgreSQL to achieve this. I refer this https://www.postgresql.org/docs/9.3/static/functions-json.html but didn't get solution
First of all, your JSON is malformed, I guess the intended was:
[
{"EMP_ID":1,"NAME":"Y","VECH_NO":4587,"SALARY":1500},
{"EMP_ID":3,"NAME":"Z","VECH_NO":4007,"SALARY":1800}
]
Assuming the following table definition:
CREATE TEMP TABLE employee_details(
"EMP_ID" integer primary key,
"NAME" text,
"VECH_NO" integer,
"SALARY" numeric
);
And a sample data (just to show the update):
INSERT INTO employee_details VALUES(1, 'X', 123, 123);
You can first use json_array_elements to make each array one row and json_populate_record to get each value as the original table type, like this:
SELECT r.*
FROM
json_array_elements('[{"EMP_ID":1,"NAME":"Y","VECH_NO":4587,"SALARY":1500},{"EMP_ID":3,"NAME":"Z","VECH_NO":4007,"SALARY":1800}]') AS a(element),
json_populate_record(NULL::employee_details, a.element) AS r;
With that, you can simple use INSERT ... ON CONFLICT UPDATE:
INSERT INTO employee_details("EMP_ID", "NAME", "VECH_NO", "SALARY")
(
SELECT r."EMP_ID", r."NAME", r."VECH_NO", r."SALARY"
FROM
json_array_elements('[{"EMP_ID":1,"NAME":"Y","VECH_NO":4587,"SALARY":1500},{"EMP_ID":3,"NAME":"Z","VECH_NO":4007,"SALARY":1800}]') AS a(element),
json_populate_record(NULL::employee_details, a.element) AS r
)
ON CONFLICT ("EMP_ID") DO
UPDATE SET
"NAME" = EXCLUDED."NAME",
"VECH_NO" = EXCLUDED."VECH_NO",
"SALARY" = EXCLUDED."SALARY"
;
The ON CONFLICT clause only works on version 9.5 or higher. Before that you have to use some tricks with loop and retry or writable common table expression (although that has race-condition issues); in any case it is a good reason to upgrade if you are on older versions.

MySQL inserting data while only knowing 1 column name

I am wanting to insert some data into a MySQL table, these are the columns:
uuid | id_1 | id_41
the "id_1" and "id_41" could be anything, all I know is the primary key (uuid) and I am wanting to be able to insert into the table while only knowing the uuid column value as I am doing this so far:
PreparedStatement newPlayer = "INSERT INTO `test` values(?);";
newPlayer.setString(1, event.getPlayer().getUniqueId().toString());
But when I test it, it doesn't add to the table and does not produce any errors. I also know that all of the other values have a default value of 0
If you want to add a row without all columns included, you need to specify the column's name
INSERT INTO `test` (`uuid`) values(?);
Simple tell to insert the column you want insert eg for uuid
INSERT INTO `test` ( `uuid`) values(?);

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