Resolve a Bad format for Time error in java? - 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.

Related

Lookup and extract db value based on input (Java & SQL Server)

New to java.
I am attempting to write a class that will input a username, run a query on the username to find the ID, and subsequently use that ID in "where clauses" on all my other classes.
This is the statement that I execute (which will only ever return a recordset of a single row):
String sqlStatement = "SELECT AccountHolderId, Passcode from CIS4720.DBO.AccountHolder " +
"where Username = '" + logonName + "'";
Here is my attempt at extracting the ID via the username...
while (rset.next())
{
if(rset.getInt("Username")==logonName){
int whosOnFirst = rset.getInt("AccountHolderId");
}
I saw another answer on the forum that says you can't assign database values to variables. If that is the case, what is a better strategy?
(Also, I realize I'm not parameterizing, but I'd like to get this working before fixing that issue. This is for a course assignment so I am not worried about hack attacks).
P. S. Thanks I fixed the double equals sign (and the extra parenthesis) in the code above.
Here are some comments about the code:
rset.getInt("Username") will get the column Username from the result but it also looks for an Integer column because of getInt. You are not selecting that column in the sql statement so will error out.
If you select it and get a string, use .equals() instead of == to compare string. Also, one = is assignment and == is comparison.
You can use getString to read Strings from the result set.
You don't need to check the username and match it since your query should return exactly that user's data so I would remove the if condition entirely and just have the getInt line there.

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

Is this the right way to use MAX Function for MySQL?

In column_1 is just numbers from 1-10 with 10 rows. I am trying to find the biggest number and take that and eventually add it to another column.
private ResultSet nrs;
nrs = stmt.executeQuery("SELECT MAX(column_1) FROM table");
while(nrs.next()){
biggestNum = nrs.getInt("column_1");
}
It keeps on throwing error 'Column "column_1" not found'.
Please help.
Replace nrs.getInt("column_1") with nrs.getInt(1)
You haven't specified a name for the value you selected, so the database will choose its own. You don't know what that name will be, so just use the column number.
Not really familiar with java but i am with sql. column_1 does not exist cause it is already aggregated. try this:
private ResultSet nrs;
nrs = stmt.executeQuery("SELECT MAX(column_1) as maxColumn1 FROM table");
while(nrs.next()){
biggestNum = nrs.getInt("maxColumn1");
}
But im pretty sure there is a better way to do this

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

getdate() query via resultset throwing no current row exception

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.

Categories

Resources