I am trying to fetch records from oracle db. I have a select query which has an order by clause implemented. Now when I fire the query on the toad i get the results in correct order. i.e the order of the records at 10:00 AM is like
Record 1, Record 2,Record 3 and at 10:05 its Record 1, Record 2, Record 3. This is what i need.
Now when iam fetching it through java code, JDBC . I try to iterate the resultset, but here at 10:05 am I am getting the order like Record 2, Record 1, Record 3. Due to this when i am adding the records to the arraylist the order is not mantained.
I dont want to sort the records of arraylist after adding.
Can someone please let me know why using jdbc the records are not fetched in the order we can see using toad ?
Sample code
try{
List<TestObjVO> testResults = new ArrayList<TestObjVO>();
double statusValue = 0;
//Connection code
pstmt = conn.prepareStatement(QUERY);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
testObj = new TestObjVO();
String date = rs.getString(1);
String status = rs.getString(2);
String svc_nm= rs.getString(3);
if("SUCCESS".equalsIgnoreCase(status)){
statusValue = 1;
}else if("ERROR".equalsIgnoreCase(status)){
statusValue = -1;
}
testObj.setTime(date);
testObj.setStatus(statusValue);
testObj.setSvc_nm(svc_nm);
testResults.add(testObj);
}
SELECT query
SELECT to_char(PROBING_DATE,'DD-MM-YYYY HH24:MI:SS') AS PROBING_DATE, STATUS, SERVICE_NAME FROM TABLE_NAME WHERE PROBING_DATE >= (sysdate-30/1440) ORDER BY PROBING_DATE,SERVICE_NAME
Table
create table TABLE_NAME(
probing_date TIMESTAMP(6) not null,
status VARCHAR2(8) not null,
service_name VARCHAR2(128) not null
)
Change your select to something like this:
SELECT to_char(PROBING_DATE,'DD-MM-YYYY HH24:MI:SS') AS PROBING_DATE_STR,
PROBING_DATE,
STATUS,
SERVICE_NAME
FROM TABLE_NAME
WHERE PROBING_DATE >= (sysdate-30/1440)
ORDER BY PROBING_DATE,SERVICE_NAME;
Note there's an extra field returned and is the raw TIMESTAMP field.
Related
I am using MySql database which has one table 'tradeinfo'.
Table structure:
Date TradeCode
2017.01.01 0001
2017.02.05 0002
2017.03.05 0001
My sql to find lastest trading day of the one tradecode is
SELECT TradeCode, MAX(date) most_recent_time FROM tradeinfo WHERE TradeCode = '0001'
I test the sql in Mysql db and can get right result which is "2017.03.05 0001"
But for my java code which is "lastestdbrecordsdate = rs.getDate("MOST_RECENT_TIME"); ", It ever return right result. But few days later, when run it again, I always get NULL.
My java code is:
Connection con = DriverManager.getConnection("jdbc:mysql://...",user,password);
String sqlstatement = "SELECT TradeCode, MAX(date) most_recent_time FROM tradeinfo WHERE TradeCode = '0001' ";
PreparedStatement sqlstat = con.prepareStatement(sqlstatement);
ResultSet rsquery = sqlstat.executeQuery(sqlstatement);
CachedRowSetImpl cachedRS = new CachedRowSetImpl();
cachedRS.populate(rsquery);
while(cachedRS.next() ) {
System.out.println(cachedRS.getMetaData().getColumnCount());
Date lastestdbrecordsdate = cachedRS.getDate("MOST_RECENT_TIME");
}
Is the problem that I config the mysql wrongly or I write wrong java code?
Thanks all!
You have several problems here. First, you should be using the following query:
SELECT MAX(date) most_recent_time FROM tradeinfo WHERE TradeCode = '0001'
Adding TradeCode to the select list doesn't make any sense because it is not an aggregate, but rather each record has a value for this column.
With regard to why you are getting null results, you need to call ResultSet#next() to advance the cursor to the first line:
Connection con = DriverManager.getConnection("jdbc:mysql://...", user, password);
Statement sqlstat = con.prepareStatement(sqlstatement);
ResultSet rsquery = sqlstat.executeQuery(); // DON'T pass anything to executeQuery()
if (rsquery.next()) {
Date lastestdbrecordsdate = rs.getDate("most_recent_time");
}
Another problem I just noticed is that you were passing in the query string to your call to Statement#executeQuery(). This is wrong, and you should not be passing anything to this method.
Following is my code(Re-constructed) which select & update STATUS field depending upon the conditions. (Using Servlets, Oracle as Backend and JDBC driver)
ResultSet rs=null;
String query = "select A.NAME, A.ADDRESS, A.STATUS, B.CLASS from TABLE_ONE A, TABLE_TWO B where A.STATUS='N'";
pstmt = con.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
while(rs.next())
{
String name = rs.getString("NAME");
String address = rs.getString("ADDRESS");
String class = rs.getString("CLASS");
String msg = //Other statements to check what status to be set
if(msg.equals("OK"))
rs.updateString("STATUS", "S");
else
rs.updateString("STATUS", "E");
rs.updateRow();
}
I am getting the error while updating:
java.sql.SQLException: Invalid operation for read only resultset: updateString
Any suggestions will be appreciated.
Update 1:
The same code was working when select statement was selecting data from single table, so is there any issue when selecting data from two tables in single query?
[Note: As #javaBeginner has mentioned in comments it will work only for one table.]
The following limitations are placed on queries for enhanced result sets. Failure to follow these guidelines will result in the JDBC driver choosing an alternative result set type or concurrency type.
To produce an updatable result set (from specification):
A query can select from only a single table and cannot contain any join operations.
In addition, for inserts to be feasible, the query must select all non-nullable columns and all columns that do not have a default value.
* A query cannot use "SELECT * ". (But see the workaround below.)
* A query must select table columns only. It cannot select derived columns or aggregates such as the SUM or MAX of a set of columns.
To produce a scroll-sensitive result set:
A query cannot use "SELECT * ". (But see the workaround below.)
A query can select from only a single table.
Try This :
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
//Execute a query
String sql = "select A.NAME, A.ADDRESS, A.STATUS, B.CLASS from TABLE_ONE A, TABLE_TWO B where A.STATUS='N'";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set
rs.beforeFirst();
while(rs.next())
{
String name = rs.getString("NAME");
String address = rs.getString("ADDRESS");
String class = rs.getString("CLASS");
String msg = //Other statements to check what status to be set
if(msg.equals("OK"))
rs.updateString("STATUS", "S");
else
rs.updateString("STATUS", "E");
rs.updateRow();
}
Just changed Prepared statement to create statement
SELECT * makes the resultSet readonly. SELECT COLUMN_NAME makes it updatable.
So instead of SELECT * FROM TABLE use SELECT COLUMN1, COLUMN2, ... FROM TABLE.
In PostgreSQL user is a reserved keyword that is used in an internal table, however I also have a separate user table in my own database that I need to use. Whenever I try to execute INSERT or UPDATE statements on the table, it generates the following error: The column name 'id' was not found in this ResultSet.
This is the Java code I am currently using:
PreparedStatement stat1 = conn.prepareStatement("SELECT id FROM user;");
PreparedStatement stat2 = conn.prepareStatement("UPDATE user SET date_created = ? , last_updated = ? , uuid = ? WHERE id = ?;");
ResultSet rs = stat1.executeQuery();
while(rs.next()){
UUID uuid = UUID.randomUUID();
String tempId = uuid.toString();
stat2.setTimestamp(1, curDate);
stat2.setTimestamp(2, curDate);
stat2.setString(3, tempId);
stat2.setLong(4,rs.getLong("id"));
stat2.executeUpdate();
}
So my question is, how could I insert or update the values in my personal user table without interfering with the keyword restriction?
Use this:
prepareStatement("UPDATE \"user\" set date_created = ?")
Or, better yet, rename your user table to something else, like users:
ALTER TABLE "user" RENAME TO users;
Escape the table name like this
select * from "user";
I am trying to select data from my db, but instead of getting a certain field I get "".
My table name is locations and it's look like this:
id - int,
location - varchar and time - timestamp.
I would like to select the last location based on the time, here is my code:
this.select = this.conn.createStatement();
ResultSet result = select.executeQuery("SELECT location FROM locations ORDER BY time DESC Limit 1");
result.next();
System.out.println(result.getString(1));
I remind you the output is "";
To identify the column in your resultSet you can use:
result.getString("location");
did u try ?
System.out.println(result.getString(0));
I am wanting to update all the rows in the RESULTSET from the SELECT in one single UPDATE query.
Here is what I have come up with so far:
SELECT id_queue, status FROM table WHERE status IN (0,2) ORDER BY status, id_queue ASC FOR UPDATE;
UPDATE table SET status = 97 WHERE id_queue= " + id_combined + ";
So, I guess I need to take all the id_queue ids, put them together like 1,2,3,4,5,6,7,8 into id_combined.
Any idea the best way to do this in JAVA?
NOTE: I am not just trying to update all with status 0 & 2 to 97, I want to use the select resultset somewhere else.
Not sure what SQL dialect you are using, but this is worth a try:
update table set status = 97 where ID_queue in
(SELECT id_queue FROM table WHERE status IN (0,2))
Use a StringBuilder to collect the id numbers returned in the ResultSet, and then use this to build an update query.
First, execute the query and collect the ID's.
StringBuilder ids = new StringBuilder();
Statement statement = this.conn.createStatement();
statement.executeQuery("SELECT id_queue, status FROM table WHERE status IN (0,2) ORDER BY status, id_queue ASC;");
ResultSet rs = statement.getResultSet();
while (rs.next()) {
if (ids.length() > 0)
ids.append(',');
ids.append(rs.getInt("id_queue"));
}
// use the resultset for whatever else you want
rs.close();
Then, perform the update.
if (ids.length() > 0) {
statement = this.conn.createStatement();
statement.executeUpdate("UPDATE table SET status = 97 WHERE id_queue In ("+ids.toString()+");");
}
One approach to do this is a nested query. That is, you can put a SELECT inside your UPDATE sort of like this:
UPDATE table SET status = 97 WHERE id_queue IN (SELECT id_queue
FROM table
WHERE status IN(0,2))
Google for sql 'nested query' or 'subquery' for more info.
My thought would be something along the lines for (not working code)
List<Integer> ids = new ArrayList<Integer>();
for(Row row : ResultSet.rows()) {
ids.add(row.get("id_queue");
}
String sql = "UPDATE table SET status = 97 WHERE id_queue IN (" +
StringUtils.join(ids, ",") +
")";
Using the StringUtils class from Apache.
Obviously, since you said you don't want to convert ALL items in the ResultSet to status 97:
You can't just have an SQL query that does the SELECT/SET at the same time (unless you can formulate in SQL what the additional criteria are), and
You'll need up modify the for loop to select out only the rows you actually want to modify
For completeness sake, the following would do the update (if you wanted to modify all rows) with pure SQL
UPDATE table SET status = 97
WHERE status IN (0,2)
to avoid the error you need to give the SELECT statment an alias:
try this:
UPDATE table SET status = 97 WHERE id_queue IN (SELECT * FROM (SELECT id_queue
FROM table
WHERE status IN(0,2)) MyResult)
MyResult is an alias to the select query