getdate() query via resultset throwing no current row exception - java

I have a problem here, what i wanna do is getting current date and a column from a table. Here is my code so far :
s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rset = s.executeQuery("select getdate() as date, tglpengiriman from orders");
java.sql.Date date = rset.getDate("date");
java.sql.Date tglkirim = rset.getDate("tglpengiriman");
And throwing exception "no current row in ResultSet" in line 3 of my code above.
What's wrong with my code? Missunderstanding usage of ResultSet, maybe?
Thanks for any answer...
EDIT:
answered. Please see post from #Christopher below. Thanks

You need to call ResultSet.next before you call any of the ResultSet.get* methods. Take a look at the documentation for Statement, ResultSet, etc. Also be sure to close all your resources in a 'finally' block.

You need to call
rset.next() before getting the data from the result set. It is also wise to check that rset.next() returned true.

Iterate Your data of result set Like this
while (resultSet.next()) {
java.sql.Date date = rset.getDate("date");
java.sql.Date tglkirim = rset.getDate("tglpengiriman");
}
because initial position of result set is always before first record i.e at beginning of first record , this resultSet.next() makes your result set to point to the first record.

Related

Strange behaviour on select query on date columns

A strange behaviour of select query just came up on my way while im doing a task for the uni.Im pulling data from a table i got on my oracle db.
selectString = "select * from reservation";
prestatement = dbConnection.prepareStatement(selectString);
rs = prestatement.executeQuery(selectString);
while (rs.next()) {
String rdate = rs.getString("reservdate").substring(0, 10);
jComboBox1.addItem(rdate);
//....
//....etc..
The thing is that what is displayed on my combo box is a think like '1999-10-10'
After that i have to pull some data where i must select the ones with the date of the selected item on the combo box.Well there's my problem.
String x = String.valueOf(jComboBox1.getSelectedItem());
selectString="select * from reservation where reservdate='"+x+"'";
//...etc..
After i run that im getting an sql exception with message : Message: ORA-01861: literal does not match format string
I searched a little bit the web and found that if i run this select query everything works fine
selectString="select * from reservation where reservdate='10-OCT-99'";
So my question is, what is the best way to make this work.I mean should i try edit all the dates from combo box to this format? or im doing something wrong all the way and should change that?
Thanks in advance.
You can either:
1- Override your related class' (whatever object that getSelectedItem returns, in this particular case its already a String and you may not need that String.valueOf() call) toString method to achieve the needed format of yours. (Kind of bad to do)
2- Let Oracle DB handle it with its TO_DATE function (Kind of a better practice to do)
"TO_DATE(yourDateString,dateFormat)"
String date = String.valueOf(jComboBox1.getSelectedItem());
selectString="select * from reservation where reservdate= TO_DATE('" + date + "','DD-MON-YY')";
And to prevent SQL injections, using the latter approach with a PreparedStatement would look like this:
String date = String.valueOf(jComboBox1.getSelectedItem());
String selectString="select * from reservation where reservdate= TO_DATE(?,'DD-MON-YY')";
PreparedStatement preStatement = dbConnection.prepareStatement(selectString);
preStatement.setString(1,date);
ResultSet rs = preStatement.executeQuery();
Official Docs

How can I check if a unique value is already in a MySQL table from jFrame?

I have this on a jFrame Button:
label.setVisibility(false);
ResultSet rs = state.executeQuery("SELECT Str_Column FROM Table WHERE Str_Column = '"+ jTextField.getText() +"'");
//check for the existance
if(rs.getString("Str_Column").equals(jTextField.getText())){
label.setVisibility(true);
}
else{
new frameForSucceedInput.setVisibility(true);
}
if the if-case goes true or not always displays the succeed window and thats what i don't want to happen, it tells something about ResultSet null cause conflicts so then i tried another way:
if(state.execute("SELECT Str_Column FROM Table WHERE Str_Column = '"+ jTextField.getText() +"'")){
label.setVisibility(true);
}
else{
new frameForSucceedInput.setVisibility(true);
}
the state.execute("SQL") method says:
return true if the query contains results, return false if the query is a update or no contain results
i've tried rs.next() and a lot of things like instead of else do another if(rs==null) but does not work, please help
A quite generic and lighter way is to use the SQL count function .
select count(*) from table where str_Column = ?
You will get that way one record with one value and if the value is higher than 0 then you can show the frame.
Note:
You should use prepared statement so you can set parameters in the query (did you notice the question mark?) instead of concatenating the elements of the query.
You shouldn't mix the code related to the presentation (Swing) with the code related to the DB...but I think you will learn it later.

PreparedStatement

I am using PreparedStatement's setString method to set values for the start and end dates in a sql query.
String sql = "..... " AND tableA.time BETWEEN ? " +
" AND ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, startDate);
st.setString(2, endDate);
The values however are not being set. I understand that normally there is an equals sign:
"tableA.member_id = ?" +"
How do I than call setString method when I am using a 'Between' operator in the sql statement? Hope someone can advise. Thank you.
See http://docs.oracle.com/cd/B28359_01/server.111/b28286/conditions011.htm
"BETWEEN" can be used with datetime data types. However, if tableA.time is a datetime field of some kind (Timestamp, etc.), using st.setString(...) won't work. You need to use setDate(dt) or setTimestamp(ts) instead. See Using setDate in PreparedStatement for more info.
Use setDate.
Is your startDate and endDate a java.util.Date object?
If it is, you can use this code.
st.setDate(1, new java.sql.Date(startDate.getTime()));
st.setDate(2, new java.sql.Date(endDate.getTime()));
If it is not. Convert that first ro java.util.Date object.
BETWEEN expects its arguments to have a type that is compatible with the column being tested. Giving it string arguments for a date column won't work.
You could add a function to the SQL in order to convert the string to a date (I don't know what database you're using, this example uses Oracle's to_date function):
from tableA.time BETWEEN to_date(?, 'yyyy/mm/dd') AND to_date(?, 'yyyy/mm/dd')
Alternatively you could leave the SQL alone and use setDate on the PreparedStatement, like:
setDate(1, new SimpleDateFormat("yyyy/MM/dd").parse(startDate));
This second way is more usual, it has the advantage of avoiding having to add a date-conversion function (that may be non-standard) to your SQL.
But you would have to do the conversion on one side or the other. The database's SQL parser won't convert it for you. If the database took responsibility for the conversion and there was a mistake it could introduce data errors silently, the less error-prone alternative is for the application developer to tell the database how the date string should be converted.

How to get actual datatype using ResultSet object?

I am using java's ResultSetMetaData.getColumnTypeName() method to find the resultset datatype of the dynamically constructed query. But for the below query
Select Adddate('2013-12-10',10) // MySQL Query
It return "Char". Why it so?? I expect Date.
Experts please help.
Thanks
You can try to cast your result to DATE:
SELECT CAST(ADDDATE('2013-12-10',10) as DATE);
I think ADDDATE behaves just like DATE_ADD, which returns string in this case:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

Resolve a Bad format for Time error in java?

i'm working with java to extract values of a time column in table in mysql.
the code below show the query i do send.
String query="select id,time from table where Hour(time)<=32 ";
ResultSet res = stmt.executeQuery(query);
while (res.next()) {
String id = res.getString(1);
Time tc = res.getTime("time");
System.out.println(tc);
}
the time values can be negative (-56:00:00 meaning that we surpassed a certain delay.
the problem is that I get: java.sql.SQLException: java.sql.SQLException: Bad format for Time '-05:48:49' in column 2.
thanks for your help.
If the conversion done by the ResultSet implementation does not work for negative time values then you still can read the value as a String and implement your custom method to convert the String to a Date (and vice versa):
String query="select * from table where Hour(time)<=32 ";
ResultSet res = stmt.executeQuery(query);
while (res.next()) {
String id = res.getString(1);
Time tc = convertToDate(res.getString("time"));
System.out.println(tc);
}
// ....
}
private Time convertToDate(String s) {
// implement magic here
}
As answered in your previous question you need to store and handle it as seconds which is stored as a signed integer.
The time type cannot be negative. You also cannot do math on a varchar/string and massaging it forth and back to a workable format as suggested by Andreas_D would only add unnecessary overhead. A signed integer is really the best datatype you can use for this. Use PreparedStatement#setInt() to store it and use ResultSet#getInt() to obtain it.
Maybe this answer is so late. But you can solve it just concating a string to the field you want.
I mean:
select id,concat(time,'') from table where Hour(time)<=32
Regards
Saul Hidalgo.
I think the problem is on the query itself.
When you run direcly the query [select * from table where Hour(time)<=32] does it not return you an error? I imagine the error is on the where clause [Hour(time)<=32]
The resultset does not have any information about the where clause. It just returns all the columns.
You need to check the columns return to check if you are not returning some strange type.

Categories

Resources