I have database A for caching and B at the server, so I want to send a row from A to B and for that I need to generate the insert statement for already existed row in A.
below is what I want to accomplish
get insert select * from table where myId = 5;
and it should return
insert into table(myId,Col1,Col2,...) VALUES (5,'value1','value2',...);
I already had looked into this and this, that are not addressing my question.
Thanks in advance!
The sqlite3 command-line shell can generate such an output, but without column names, for queries:
sqlite> .mode insert MyTableName
sqlite> SELECT * FROM MyTable WHERE ID = 5;
INSERT INTO MyTableName VALUES(5,'value',NULL);
If you want the column names, you have to generate them manually:
SELECT 'INSERT INTO MyTable(a, b, c) VALUES (' ||
quote(a) || ',' ||
quote(b) || ',' ||
quote(c) || ');'
FROM MyTable
WHERE ID = 5;
--> INSERT INTO MyName(a, b, c) VALUES (42,'value',NULL);
(The same string operations could be done in Java.)
If your program does not know the exact database schema, you can read the list of columns for each table with PRAGMA table_info, and construct the statement from that:
> create table MyTable(myId, Col1, Col2, [...]);
> pragma table_info(MyTable);
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 myId 0 0
1 Col1 0 0
2 Col2 0 0
3 ... 0 0
Related
I am using the below query in a prepared statement. Earlier I was using in procedure and using callable but now I am trying to use select query in jdbc prepared statement.
I know in preparestatement we write insert into abc values(?,?,?);
but here I have insert-select. same variable has been used many places. in this query I have 2 variable
p_entity_type and p_update_mode
INSERT INTO dynamicEntitynotgett
(entity_type, entity_id, entity_code, synonyms, action)
WITH data_view AS
( -- ITEM table
SELECT 'ITEM' entity_type, -- This separates inserted values
item_id data_id,
item_name data_name,
item_desc data_desc,
creation_date
FROM itemde
UNION ALL
-- ORG table
SELECT 'ORG' entity_type, -- This separates inserted values
org_id,
org_name,
org_desc,
creation_date
FROM orgde
UNION ALL
-- Feature table
SELECT 'FEATURES' entity_type, -- This separates inserted values
FEATURE_id data_id,
FEATURE_NAME data_name,
FEATURE_DESC data_desc,
CREATION_DATE
FROM FEATURESDE
)
SELECT upper(t.entity_type),
t.data_id,
t.data_name,
t.data_desc,
CASE lower(p_update_mode)
WHEN 'INCREMENTAL' THEN
CASE
WHEN t.creation_date > b.last_update_date THEN
'update'
WHEN t.creation_date < b.last_update_date THEN
'add'
END
WHEN 'full' THEN
'add'
END action
FROM data_view t
LEFT JOIN ODA_REFRESH_DETAILS b
ON b.entity_type = t.entity_type
AND lower(p_update_mode )='incremental'
WHERE (upper(p_entity_type) = t.entity_type OR p_entity_type IS NULL)
AND (lower(p_update_mode) = 'full'
OR (lower(p_update_mode) = 'incremental' AND b.entity_type IS NOT NULL)
);
I will receive p_entity_type and p_update_mode from upper stream. which solution would be better? Resultset or Preparedstatement and how can I replace those values in query or use setXXX().
I think you are looking for namedParameterStatement. This would allow you to name the parameters.
I'm not exactly sure what you are referring to in your statement, but for instance, this line:
SELECT 'ITEM' entity_type
could be replaced with:
SELECT :ITEM as entity_type
where :ITEM is passed in just like a ?, but could be used multiple times in the statement.
I'm using MySQL and fetching a few different values from a table and then perform some basic math on it. Currently three seperate SELECT statements are in use and afterwards I perform some simple addition and subtraction with the outputs I get in Java.
I'm trying to optimize my code but sadly I gotta admit I'm a complete SQL noob. I'm pretty sure there's a way to join these select querys and the calculations so that I actually only get one output but I've not been able to find it.
My table looks something like this:
ID | value | inc | timestamp
--------------------------------------
0 | 5 | 4 | 2018-02-01 10:28:21
1 | 8 | 3 | 2018-02-01 10:28:47
...
My code currently looks like this:
int maxValue = MySQL.executeQuery("SELECT MAX(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())");
int minValue = MySQL.executeQuery("SELECT MIN(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())");
int minInc = MySQL.executeQuery("SELECT `inc` FROM `table` where ID = id AND value = minValue");
int output = maxValue - minValue + minInc;
Is there a way to shorten it to a single
int output = MYSQL.executeQuery( ??? );
?
Simply do select (select ...) - (select ...) + (select ...)
In your case, you can do( not tested in real environment )
select (SELECT MAX(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())) - ( SELECT MIN(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())) + (SELECT `inc` FROM `table` where ID = id AND value = minValue)
First off, there's something funky going on with the maxValue and minValue selects. The Max() and Min() operators will give you the max and min values of a given column of a given set of rows. Using one of these operators with such a specific where (by what seems to be a table's primary key) is probably not what you want to be doing.
Now, answering your question, I think you could do something along the lines of:
SELECT MAX('value') as max, MIN('value') as min
FROM `table` as t
WHERE ...
to "join" (careful with this word) the first 2 queries. This is simple select syntax: usually, there's no problem with selecting more than a column or an aggregate function at a time. Or, something like:
SELECT `inc`
FROM `table`
WHERE ID = id AND
value = (SELECT MIN('value') FROM 'table' WHERE ...)
to "join" the last two.
Single statement is possible using INNER JOIN since you are using a single able. Try this
SELECT MAX(`a.value`)-(MIN(`a.value`)+b.`inc`) AS Output
FROM `table` a
INNER JOIN `table` b ON a.ID=b.ID
AND a.ID = idvalue AND `a.timestamp` >= TIMESTAMPADD(a.DAY,-3,NOW())
AND b.value=(select MIN(value) from table WHERE ID=id);
There are 10 columns. After every 24 hours, data present in column10 should move to column9, column9 data should move to column8, so on and so forth.
How do I achieve this?
You need to something like this and update the records:
take a variable that counts the number of records
num = select count(*) from <tablename>
for (i=num;i>num;num--) {
Insert into <tablename> (columns name comma separated...)
values (select (same columns comma separated...)
from <same tablename> where id=num) where id=num-1;
}
and let me know, what about the first column.
Just create another table with a different name and inserting the data for column's in whatever way you want.
-- creating myTable
Create table myTable (column1 int (11),column2 int (11),column3 int (11),column4 int (11),column5 int (11),
column6 int (11),column7 int (11),column8 int (11),column9 int (11),column10 int (11) );
insert into myTable values(1,2,3,4,5,6,7,8,9,10);
CREATE TABLE myTable_temp (column1 int (11),column2 int (11),column3 int (11),column4 int (11),column5 int (11),
column6 int (11),column7 int (11),column8 int (11),column9 int (11),column10 int (11) );
insert into myTable_temp
SELECT column2,column3,column4,column5,column6,column7,column8,column9,column10,column1
FROM
myTable ;
-- // Note: First create table then insert, "Create table select" will not work as required.
Then drop the original table and rename the _temp table to original table.
DROP TABLE tableName ;
RENAME table tableName_temp to tableName ;
select * from myTable ;
-- column1 column2 column3 column4 column5 column6 column7 column8 column9 column10
-- 2 3 4 5 6 7 8 9 10 1
An for running the code After every 24 hours from JAVA you can use scheduler to call your
function in which your SQL code is written.
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your SQL code here
}
},
5000
);
Or you can use the below link to see for more options.
java: run a function after a specific number of seconds
I have a table with [primary key counters] for [per page comments in another table].
These primary keys are per page: for each page, comment IDs start on 1.
I'd like to atomically allocate 10 IDs to write 10 new comments.
— Can I do this with PostgreSQL and JDBC?
(And do you have any links to any example / the relevant JDBC documentation?)
I've found only examples about how returning the primary key of a newly inserted row, using some getGeneratedKeys which doesn't seem useful in my case.
***
I think the SQL UPDATE statement would look something like this:
update PAGES
set NEXT_COMMENT_ID = NEXT_COMMENT_ID + 10
where PAGE_ID = ? <-- next-comment-id is *per page*
returning NEXT_COMMENT_ID into ?
So, different threads and servers won't attempt to reuse/overwrite the same IDs (right?).
This is supported without using the execute() and getResult() methods on the Statement object:
Something like this (barring any error handling):
String sql = "update ... returning ...";
boolean hasResult = statement.execute(sql);
int affectedRows = 0;
ResultSet rs = null;
if (hasResult) {
rs = statement.getResultSet();
}
int affectedRows = statement.getUpdateCount();
As you know what the statement does, this should be OK. Dealing with an "unknown" SQL statement is a bit more complicated because you need to call getMoreResults() and getUpdateCount() in a loop. See the Javadocs for details.
So you're wanting the following structure?:
x = page primary key
y = comments primary key
Page Table
x
-
1
2
3
4 etc
Comments Table
x y
- -
1 1
1 2
1 3
1 4
2 1
2 2
2 3
etc?
It would make most sense to have a foreign key structure here with an upper limit on the child records.
Creating a stored function that does update ... returning ... into works:
create or replace function INC_NEXT_PER_PAGE_REPLY_ID(
site_id varchar(32), page_id varchar(32), step int) returns int as $$
declare
next_id int;
begin
update DW1_PAGES
set NEXT_REPLY_ID = NEXT_REPLY_ID + step
where SITE_ID = site_id and PAGE_ID = page_id
returning NEXT_REPLY_ID into next_id;
return next_id;
end;
$$ language plpgsql;
And calling it like so:
statement = connection.prepareCall(
"{? = call INC_NEXT_PER_PAGE_REPLY_ID(?, ?, ?) }")
statement.registerOutParameter(1, java.sql.Types.INTEGER)
bind(values, statement, firstBindPos = 2) // bind pos no. 1 is the return value
statement.execute()
nextNewReplyIdAfterwards = statement.getInt(1)
Related documentation:
http://jdbc.postgresql.org/documentation/91/callproc.html
class CallableStatement and registerOutParameter()
StackOverflow question: How to return updated rows from function
To make the table contain a logical order then you may need to create a composite key and a foreign key within the child table.
sd=# create table x (x int);
CREATE TABLE
sd=# create table y (x int, y int);
CREATE TABLE
sd=# alter table x add primary key (x);
NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "x_pkey" for table "x"
ALTER TABLE
sd=# alter table y add foreign key (x) references x (x);
ALTER TABLE
sd=# alter table y add primary key (x,y);
NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "y_pkey" for table "y"
ALTER TABLE
sd=# insert into x values (1);
INSERT 0 1
sd=# insert into x values (2);
INSERT 0 1
sd=# insert into x values (3);
INSERT 0 1
sd=# insert into y values (1,1);
INSERT 0 1
sd=# insert into y values (1,2);
INSERT 0 1
sd=# insert into y values (1,3);
INSERT 0 1
sd=# insert into y values (1,1);
ERROR: duplicate key value violates unique constraint "y_pkey"
DETAIL: Key (x, y)=(1, 1) already exists.
sd=# select * from x;
x
---
1
2
3
(3 rows)
sd=# select * from y;
x | y
---+---
1 | 1
1 | 2
1 | 3
(3 rows)
This should get you where you want to be?
You're doing an update but the statement generates results, so use executeQuery() instead of executeUpdate(). That's the real difference between the calls: executeQuery() deals with statements that yield a ResultSet; while executeUpdate() returns count of the number of rows affected.
I am trying to create a nested SELECT SQL statment. I store all value and id and want to select rows that satisfy multiple values. How can I generate a SELECT statement using Java? For example,
ID VALUE
1 RED
2 BIG
1 SMALL
1 SMOOTH
2 TALL
.....
To select an item that is both red and small the statement would be:
SELECT *
FROM table
WHERE table.value = RED AND
id IN (SELECT *
FROM table
WHERE table.value = SMALL AND id IN (...))
This type of problem is called Relational Division
SELECT ID
FROM tableName
WHERE VALUE IN ('SMALL','SMOOTH')
GROUP BY ID
HAVING COUNT(*) = 2
SQLFiddle Demo
the query above will result 1 since the ID contains both records.
If no unique constraint was enforce on value for every ID, DISTINCT is required.
SELECT ID
FROM tableName
WHERE VALUE IN ('SMALL','SMOOTH')
GROUP BY ID
HAVING COUNT(DISTINCT VALUE) = 2
SQLFiddle Demo
SQLFiddle Demo (with duplicate)
OTHER(s)
SQL of Relational Division
select ID
from MyTable
where VALUE in ('RED', 'SMALL')
group by ID
having count(distinct VALUE) = 2
SQL Fiddle Example
Results:
| ID |
------
| 1 |
Here is a general way to approach this:
select id
from t
group by id
having max(case when value = 'Red' then 1 else 0 end) = 1 and
max(case when value = 'Small' then 1 else 0 end) = 1
In other words, membership in the set becomes a clause in the having statement. These can be both inclusion and exclusion (use = 0 instead of = 1) and optional (use or instead of and).