retrieve database into JTextField - java

i'm doing a project where i need to retrieve data from one field of access and display it on JTextField and its serial no.select fieldname from tablename
but it'l select all rows.also how to retrieve data(whole row) with random serial number

For the query to select the field data,
SELECT fieldName FROM tableName WHERE columnName = 'columnValue';
Here, columnName should be something like the primary key and columnValue will be a unique value (like a serial number). Then it will return the field data associated with the row with the specific columnValue.
For setting it into the JTextField,
if(resultSet.first()) {
jTextField.setText(resultSet.getString(0));
}
Here, resultSet should return only one value (with the query specified above).
As for your other question, if your serials are irregular, get all the serials from the table:
SELECT serials FROM yourTable;
And then add them to a Collection (like a Vector). Then write an algorithm to generate a random index and retrieve the data from the Collection with that index (vector.elementAt([yourIndex])).
Then again query the table in the database for the row associated with that serial:
SELECT FROM yourTable WHERE serialNo = 'theValueYouGot';
...and you'll get the relevant row.

Related

How can I access a value when inserting into a table?

I'm trying to write a java sql query, the simplified table would be table(name,version) with a unique constraint on (name, version).
I'm trying to insert a row into my database with a conditional statement. Meaning that when a entry with the same name exists, it should insert the row with same name and its version increased by 1.
I have tried with the following:
INSERT INTO table(name,version)
VALUES(?, CASE WHEN EXISTS(SELECT name from table where name=?)
THEN (SELECT MAX(version) FROM table WHERE name = ?) +1
ELSE 1 END)
values are sent by user.
My question is, how can I access the 'name' inside the values so I could compare them?
If you want to write this as a single query:
INSERT INTO table (name, version)
SELECT ?, COLAESCE(MAX(t2.version) + 1, 1)
FROM table t2
WHERE t2.name = ?;
That said, this is dangerous. Two threads could execute this query "at the same time" and possibly create the same version number. You can prevent this from happening by adding a unique index/constraint on (name, version).
With the unique index/constraint, one of the updates will fail if there is a conflict.
I see at least two approaches:
1. For each pair of name and version you first query the max version:
SELECT MAX(VERSION) as MAX FROM <table> WHERE NAME = <name>
And then you insert the result + 1 with a corresponding insert query:
INSERT INTO <table>(NAME,VERSION) VALUES (<name>,result+1)
This approach is very straight-forward, easy-to-read and implement, however, not really performant because of so many queries necessary.
You can achieve that with sql alone with sql analytics and window functions, e.g.:
SELECT NAME, ROW_NUMBER() over (partition BY NAME ORDER BY NAME) as VERSION FROM<table>
You can then save the result of this query as a table using CREATE TABLE as SELECT...
(The assumption here is that the first version is 1, if it is not the case, then one could slightly rework the query). This solution would be very performant even for large datasets.
You should get the name before insertion. In your case, if something went wrong then how would you know about it so you get the name before insert query.
Not sure but you try this:
declare int version;
if exists(SELECT name from table where name=?)
then
version = SELECT MAX(version) FROM table WHERE name = ?
version += 1
else
version = 1
end
Regards.
This is actually a bad plan, you might be changing what the user's specified data. That is likely to not be what is desired, maybe they're not trying to create a new version but just unaware that the one wanted already exists. But, you can create a function, which your java calls, not only inserts the requested version or max+1 if the requested version already exists. Moreover it returns the actual values inserted.
-- create table
create table nv( name text
, version integer
, constraint nv_uk unique (name, version)
);
-- function to create version or 1+max if requested exists
create or replace function new_version
( name_in text
, version_in integer
)
returns record
language plpgsql strict
as $$
declare
violated_constraint text;
return_name_version record;
begin
insert into nv(name,version)
values (name_in,version_in)
returning (name, version) into return_name_version;
return return_name_version;
exception
when unique_violation
then
GET STACKED DIAGNOSTICS violated_constraint = CONSTRAINT_NAME;
if violated_constraint like '%nv\_uk%'
then
insert into nv(name,version)
select name_in, 1+max(version)
from nv
where name = name_in
group by name_in
returning (name, version) into return_name_version;
return return_name_version;
end if;
end;
$$;
-- create some data
insert into nv(name,version)
select 'n1', gn
from generate_series( 1,3) gn ;
-- test insert existing
select new_version('n2',1);
select new_version('n1',1);
select *
from nv
order by name, version;

Can you check if a column exists and perform different actions with oracle?

My table looks like the following:
id | value1 | count
I have a list of value1 in RAM and I want to do the following:
(if value1 exists in table){
count + 1}else{
insert new row into table}
Is this possible with Oracle or do I have to take it to the code, do a for loop and execute one element of the list at a time? The list contains 5 million values. I'd have to do something like this in the code:
for(int i=0; i<list.size; i++){
boolean exists = checkifexists(list.get(i));
if(exists=true){
countPlusOne(list.get(i);
}else{
createNewRow(list.get(i));
}
}
So I have to do at least two queries for each value, totalling 10m+ queries. This could take a long time and may not be the most efficient way to do this. I'm trying to think of another way.
"I load them into RAM from the database"
You already have the source data in the database so you should do the processing in the database. Instantiating a list of 5 million strings in local memory is not a cheap operation, especially when it's unnecessary.
Oracle supports a MERGE capability which we can use to test whether a record exists in the target table and populate a new row conditionally. Being a set operation MERGE is way more performative than single row inserts in a Java loop.
The tricky bit is uniqueness. You need to have a driving query from the source table which contains unique values (otherwise MERGE will hurl). In this example I aggregate a count of each occurrence of value1 in the source table. This gives us a set of value1 plus a figure we can use to maintain the count column on the target table.
merge into you_target_table tt
using ( select value1
, count(*) as dup_cnt
from your_source_table
group by value1
) st
on ( st.value1 = tt.value1 )
when not matched then
insert (id, value1, cnt)
values (someseq.nextval, st.value1, st.dup_cnt)
when matched then
update
set tt.cnt = tt.cnt + st.dup_cnt;
(I'm assuming the ID column of the target table is populated by a sequence; amend that as you require).
In Oracle, we could use a MERGE statement to check if a row exists and do insertion only if it doesn't.
First create a type that defines your list.
CREATE OR REPLACE TYPE value1_type as TABLE OF VARCHAR2(10); --use the datatype of value1
Merge statement.
MERGE INTO yourtable t
USING (
select distinct column_value as value1 FROM TABLE(value1_type(v1,v2,v3))
)s ON ( s.value1 = t.value1 )
WHEN NOT MATCHED THEN INSERT
(col1,col2,col3) VALUES ( s.col1,s.col2,s.col3);
You may also use NOT EXISTS.
INSERT INTO yourtable t
select * FROM
(
select distinct column_value as value1 from TABLE(value1_type(v1,v2,v3))
) s
WHERE NOT EXISTS
(
select 1 from
yourtable t where t.value1 = s.value1
);
You can do this by two approaches
Approach 1:
Create a temp table in database and insert all your value in RAM into that Temp Table
Write query for updating count on the basis of you main table and temp table join and
set a flag in temp table which values are updated, the value which are not updated
use insert query to insert.
Approach 2:
You can create your own data type, which accepts array of values as input:
CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
You can write procedure with your logic,procedure will take value of array as input: CREATE OR REPLACE PROCEDURE testing (t_in MyType)
First fill your RAM list in a temporary table TMP
select * from tmp;
VALUE1
----------
V00000001
V00000002
V00000003
V00000004
V00000005
...
You may use a MERGE statement to handle your logik
if key existe increase the count by 1
if key doesn't exists insert it with the initial count of 1
.
merge into val
using tmp
on (val.value1 = tmp.value1)
when matched then update
set val.count = val.count + 1
when not matched then
insert (val.value1, val.count)
values (tmp.value1, 1)
;
Note that I assume you have IDENTITY key in the column ID, so no key assignment is requeired.
In case there are duplicated record in the TMP table (more records with the same VALUE1 key) you get error as MERGEcan not hanlde more actions with one key.
ORA-30926: unable to get a stable set of rows in the source tables
If you want to count each duplicated key as one -
you must pre-aggregate the temporary table using GROUP BY and add the counts.
Otherwise simple ignore the duplicates using DISTINCT.
merge /*+ PARALLEL(5) */ into val
using (select value1, count(*) count from tmp group by value1) tmp
on (val.value1 = tmp.value1)
when matched then update
set val.count = val.count + 1
when not matched then
insert (val.value1, val.count)
values (tmp.value1, 1)

Need column names and column values from update sql before executing

I need to know the list of the column and values from the update sql using java. Code is to read a update query and take backup of the actual column values before executing the update sql. For this is need to know the column names. Please advise!
sql = update testenv.employee set gender = '2',StudentInd = '112233' where empID in (987987);
String criteriaQuery = resultset.getString("query"); // this is the update statement which is not constant and varies everytime.
String schema = StringUtils.substringBetween(criteriaQuery.toUpperCase(), "UPDATE ", ".").trim();
String table = StringUtils.substringBetween(criteriaQuery.toUpperCase(), ".", "SET").trim();
String columnName = StringUtils.substringBetween(criteriaQuery.toUpperCase(), "SET", "=").trim();
But columnName will not get the correct columns. Need to optimise the code such that i can get the entire column names from the update query.
If you're using JDBC, you can use the following:
ResultSetMetaData md = rs.getMetaData();
after getting the result set of your select statement.
http://www.roseindia.net/jdbc/jdbc-mysql/DiscriptionTable.shtml
Provides a clear example, the same applies for SQLServer databases and Oracle.

select statement returning values for non existent value in where clause

I'm trying the following query in cql.
SELECT * FROM LoadTest_Storage WHERE ItemName='NDTV_CRICKET145667657568'
AND key='NDTV_CRICKET1' LIMIT 1000
The key is existing but that itemname is not there in my table. But still it is returning the data of NDTV_CRICKET1 key.
But instead of key if i give some other column name for eg.
SELECT * FROM LoadTest_Storage WHERE ItemName='NDTV_CRICKET145667657568'
AND type='NDTV' LIMIT 1000
And such a type exists in my table but the itemname is not there then i don't get any results.
Why is it happening for key column alone?
Is it typical behavior of cassandra?

Retrieving data from a relational database

I have set up 2 two tables - table userid and table data in phpmyadmin. The userid table consists of a single column - id and the table data consists of the following columns- id|name|price. I have added an index in the column id of table userid to point to id of the table data. Now i have a user who makes certain selections inside an android application. I want to insert this data into the table data. I know i have to use jdbc and know how to enter data for table without any index. But i am confused as to how to go about doing it in the case of related tables. The userid is obtained from this link http://android-developers.blogspot.in/2011/03/identifying-app-installations.html. Would someone please tell me how to enter the data using java. (The confusion is how to enter the userid and the corresponding data ).
As long as you're aware of the user id when you're inserting a new record into the data table that's all you need. Basically you'll have:
Statement stmt = conn.createStatement();
stmt.executeUpdate( "INSERT INTO data (id, name, price) VALUES ('id from userid table', 'a name', 'a price')");
Obviously the params aren't escaped properly (they really should be) and there's no testing for errors, but that would get you started.
Then to, for example, select all the data related to a given userid, you would do something like:
Statement stmt = conn.createStatement();
stmt.executeQuery( "SELECT * FROM userid LEFT JOIN data WHERE userid.id = data.id" );

Categories