I have some data in an SQLite Database. The following queries in SQLiteBrowser give me exactly the ResultSet I want:
With TempTable0 AS (SELECT Source, Date, Value AS Close FROM FinData WHERE Type = 'Close'),
TempTable1 AS (SELECT Source, Date, Value AS Colume FROM FinData WHERE Type = ' Colume')
SELECT DISTINCT TempTable0.Date, Close, Colume FROM TempTable0
JOIN TempTable1 ON TempTable1.Date = TempTable0.Date
Now, I tried to get this working as a single query via a simple executeQuery-Method from Java and read the data in a Matrixlike-DataStructure:
String sql = "With TempTable0 AS (SELECT Source, Date, Value AS Close FROM FinData WHERE Type = 'Close'), TempTable1 AS (SELECT Source, Date, Value AS Colume FROM FinData WHERE Type = ' Colume') SELECT DISTINCT TempTable0.Date, Close, Colume FROM TempTable0 JOIN TempTable1 ON TempTable1.Date = TempTable0.Date";
Connection Conn = DriverManager.getConnection(SQLCommunication.urlDB);
Statement stmt = Conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next() ) {
String res = rs.getString("Close");
DataMatrix.get("Close").add(res);
res = rs.getString("Colume");
DataMatrix.get("Colume").add(res);
}
However, the Resultset returns null.
I suspect this is because, it cannot work with two dependent SQLite-Queries, however, I have no idea, how to solve this.
I am no expert on SQLite and Java interaction and I am really running out of ideas, right now. Do you have any sugestions? (Even maybe a tip on nesting these two statements in one so it can be executed in one shot?)
Thanks so much!
Wiwi
Related
I'm running this script in MySQL to retrieve the count of appoinments that are grouped by a specific type and month:
SELECT Type, month(Start), COUNT(Type) FROM appointments
GROUP BY Type, month(Start);
Which provides me with this table:
[1]: https://i.stack.imgur.com/sRJwx.png
This is great! Now my problem is trying to place the data into variables:
String sql = "SELECT `Type`, month(`Start`), COUNT(Type) FROM appointments " +
"GROUP BY `Type`, month(`Start`)";
try(Statement s = DatabaseConnection.getConnection().createStatement();
ResultSet rs = s.executeQuery(sql)) {
while(rs.next()) {
String typeKey = rs.getString("Type");
int monthValue = rs.getInt("month(Start)");
int count = rs.getInt("COUNT(Type)");
I get an SQLException when I run this, saying that the column "month(Type) cannot be found. I have tried with the column name "Start" and tried with just "month" and recieve the same SQLException (I know, kind of a stupid troubleshoot but worth a shot). I've looked around for some solutions but I'm falling short.
This is for a school project, so I can only use JDBC and Java specific drivers. I'd appreciate it if someone could point me in the right direction.
Try rename columns with as
sql = "SELECT `Type` as type ,
month(`Start`) as mstart,
COUNT(Type) as ctype
FROM appointments " +
"GROUP BY `Type`, month(`Start`)";
I have connected Java to SSMS and can call data from the server no problems using something like this:
String cell = "SELECT [Close] FROM ExcelData WHERE id_num = 3";
Statement st4 = con.createStatement();
ResultSet rs4 = st4.executeQuery(cell);
while (rs4.next())
{
Float close = rs4.getFloat("close");
System.out.format("%s\n", close);
}
When I replace the "SELECT [Close] FROM ExcelData WHERE id_num = 3" to "SELECT #SMA" I get the much questioned "Must declare the scalar variable #SMA.
I do not know how to do that.
Answering my own question to help others who may need to know this...
It cannot be done. The work around is to create a table in SQL and insert the variable into the table.
DROP TABLE IF EXISTS SMA
CREATE TABLE SMA (
SMA_Price DECIMAL (6,5),
)
INSERT INTO SMA VALUES (#SMA);
SELECT * FROM SMA;
You can then call "SELECT * FROM SMA" from Java.
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.
I have the following
DateFormat dformat = new SimpleDateFormat("yyyy-M-d");
dformat.setLenient(false);
Date cin = dformat.parse(cinDate);
and the sql function
create or replace function search(_checkIn date, _checkOut date) returns setof Bookings as $$
declare
r Bookings;
begin
for r in
select * from Bookings
loop
if ((_checkIn between r.checkIn and r.checkOut) or (_checkOut between r.checkIn and r.checkOut)) then
return next r;
end if;
end loop;
return;
end;
$$ language plpgsql;
The date format for the postgresql is standard (default)
create table Bookings (
id serial,
status bookingStatus not null,
pricePaid money not null,
firstName text,
lastName text,
address text,
creditCard text,
checkOut date not null,
checkIn date not null,
room integer not null,
extraBed boolean not null default false,
foreign key (room) references Rooms(id),
primary key (id)
);
and I'm trying to parse a date into the function so it can return a table for me, I seem to run into the issue of date formatting (which is why I think I'm getting this error)
org.postgresql.util.PSQLException: ERROR: syntax error at or near "Feb"
So I was wondering how would I fix this problem, I don't know how to format the date properly
EDIT:
I'm calling the query like this
try {
String searchQuery = "SELECT * FROM Rooms r where r.id not in (select * from search(" + cin +", " + cout +"))";
PreparedStatement ps = conn.prepareStatement(searchQuery);
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
so I think the error comes in because the way I format the date is wrong and postgres won't read it
It sounds like you're passing the argument by concatenating them directly into the string. This is a very bad idea, since it can lead to SQL injections. Always use PreparedStatements with the ? place-holders to pass parameters, never pass them directly by concatening them directly into the query string (more so, you'd need the ' delimiters around).
You could have something like:
PreparedStatement stmt
= con.prepareStatement("SELECT id FROM Bookings WHERE checkIn=?")
stmt.setDate(1, new java.sql.Date(cin.getTime()));
// ? parameters are indexed from 1
ResultSet results = stmt.executeQuery();
Alternatively, PostgreSQL internal date conversion is usually fairly good and flexible. You could cast the string parameter to a date with PostgreSQL:
PreparedStatement stmt
= con.prepareStatement("SELECT id FROM Bookings WHERE checkIn=CAST(? AS DATE)");
stmt.setString(1, cinDate);
ResultSet results = stmt.executeQuery();
This is flexible, but might not lead to the exact result you need depending on the date format (you can check the PostgreSQL manual for details on date conversion formats). The input format you're using should work just fine, though (Try SELECT CAST('2012-05-01' AS DATE) directly in PostgreSQL, for example, this will return a correct PostgreSQL date.)
Note that when using new java.sql.Date(cin.getTime()), you're likely to run into time zone issues. You could use java.sql.Date.valueOf(...) too.
To clarify, following your edit:
This will not work, since the dates would be part of the SQL syntax itself, not strings or dates: "SELECT * FROM Rooms r where r.id not in (select * from search(" + cin +", " + cout +"))"
You'd at least need to use ' quotes: "SELECT * FROM Rooms r where r.id not in (select * from search("' + cin +"', '" + cout +"'))". Here, to a degree, you could expect the parameters to be formatted properly, but don't do it. In addition, would would still have to cast the string using CAST('...' AS DATE) or '...'::DATE.
The simplest way would certainly be:
String searchQuery = "SELECT * FROM Rooms r where r.id not in (select SOMETHING from search(CAST(? AS DATE), CAST(? AS DATE)))";
PreparedStatement ps = conn.prepareStatement(searchQuery);
ps.setString(1, cinDate);
ps.setString(2, coutDate);
(As a_horse_with_no_name pointed out in a comment, the general query wouldn't work anyway because of your inner select.)
You already have advice concerning prepared statements and proper format.
You can also largely simplify your PostgreSQL function:
CREATE OR REPLACE FUNCTION search(_checkin date, _checkout date)
RETURNS SETOF bookings AS
$BODY$
BEGIN
RETURN QUERY
SELECT *
FROM bookings
WHERE _checkin BETWEEN checkin AND checkout
OR _checkiut BETWEEN checkin AND checkout;
END;
$BODY$ language plpgsql;
Or even:
CREATE OR REPLACE FUNCTION search(_checkin date, _checkout date)
RETURNS SETOF bookings AS
$BODY$
SELECT *
FROM bookings
WHERE _checkin BETWEEN checkin AND checkout
OR _checkiut BETWEEN checkin AND checkout;
$BODY$ language sql;
Rewrite the LOOP plus conditions to a plain SQL statement which is much faster.
Return from a plpgsql function with RETURN QUERY - simpler and faster than looping.
Or use a plain sql function.
Either variant has its advantages.
No point in using mixed case identifiers without double quoting. Use all lower case instead.
According to this page, the standard format for date/time strings in SQL is:
YYYY-MM-DD HH:MM:SS
And of course for dates you can use
YYYY-MM-DD
PostgreSQL accepts other formats (see here for some details) but there's no reason not to stick to the standard.
However, since you are getting a syntax error it sounds like you are injecting the date strings into your SQL statement without the proper quoting/escaping. Double-check that you are properly escaping your input.