Java SQL statement not given an error neither a resultset - java

I have the following SQL statement in my program:
"SELECT ANTAL_KALD,BESVARET_25_SEK,((BESVARET_25_SEK/nullif(ANTAL_KALD,0))*100) as answer_percent,TIDSPUNKT,QUEUE "
+"FROM KS_DRIFT.PERO_NKM_KØ_OVERSIGT WHERE TIDSPUNKT BETWEEN '"+start.getYear()+"-"+start.getMonthOfYear()+"-"+start.getDayOfMonth()+
"' AND '"+end.getYear()+"-"+end.getMonthOfYear()+"-"+end.getDayOfMonth()+
"'";
this doesnt give me any resultset
the test System.out.println(rs.next()) is false
However when i in my DB writes the following:
select QUEUE,
ANTAL_KALD,
BESVARET_25_SEK,
((BESVARET_25_SEK/nullif(ANTAL_KALD,0))*100) as answer_percent,
TIDSPUNKT
from KS_DRIFT.PERO_NKM_KØ_OVERSIGT Where TIDSPUNKT BETWEEN '2012-12-01' AND '2012-12-02' ORDER BY QUEUE
i get results.. So what is the problem? it is not giving me an error or anything

Assuming start and end are java.sql.Date objects(if not please convert), I advice you to use PreparedStatement with setDate() to set the date as below:
String sql = "SELECT ANTAL_KALD,BESVARET_25_SEK, "+
" ((BESVARET_25_SEK/nullif(ANTAL_KALD,0))*100) as answer_percent, "+
" TIDSPUNKT,QUEUE "
+"FROM KS_DRIFT.PERO_NKM_KØ_OVERSIGT "+
" WHERE TIDSPUNKT BETWEEN ? AND ?";
PreparedStatement qStmt=connection.prepareStatement(sql);
qStmt.setDate(1, start);
qStmt.setDate(1, end);
ResultSet rs = qStmt.executeQuery();
EDIT: To get java.sql.Date from Joda DateTime Object, please do the below:
java.sql.Date startDate = new java.sql.Date(start.toDate().getTime());
java.sql.Date endDate = new java.sql.Date(end.toDate().getTime());
Use these converted objects in the query.

Related

Why I obtain this error on a date field when I try to perform this query on SQL Server?

I am finding some difficulties trying to perform this SQL query (on Microsoft SQL Server) into a Java appliction.
So I have this method that perform a simple select query:
public void insertOrUpdate_TIRConsolidatoPolizza(QS_TirPolizza qsTir) throws Exception {
try{
log.debug("PucManager.insertOrUpdate_TIRConsolidatoPolizza");
// Reperisce i parametri della query dal parametro passato:
String numeroPolizza = qsTir.getPolizzaid().toString();
Long annoRiferimento = qsTir.getAnnoRiferimento();
String dataRiferimentoNav = qsTir.getDataRiferimentoNav() != null ? "'"+qsTir.getDataRiferimentoNav()+"'" : null;
String timestamp = qsTir.getTimestamp() != null ? "'"+qsTir.getTimestamp()+"'" : null;
String sql = "select * from TirConsolidatoPolizza" +
" where Polizzaid = " + numeroPolizza +
" and DataRiferimentoNav = " + dataRiferimentoNav;
log.debug("Query: " + sql);
PreparedStatement ps = con.prepareStatement( sql );
log.debug("Eseguo Query");
ResultSet rs = ps.executeQuery();
...................................................
...................................................
DO SOMETHING ELSE
...................................................
...................................................
}
The String sql variable value is (I see it printing it by log.debug()):
select * from TirConsolidatoPolizza where Polizzaid = 9999999999 and DataRiferimentoNav = 'Thu Jun 23 10:36:43 CEST 2016'
This query can't work because it seems that I have a problem with the DataRiferimentoNav value.
I obtain the following error message:
10:42:41 [SELECT - 0 row(s), 0.000 secs] [Error Code: 241, SQL State: S0001] Conversion failed when converting date and/or time from character string.
The DataRiferimentoNav (it is a datetime on the db table) value is taken from the qsTir.getDataRiferimentoNav() object field that is a String (I can't change it) representing a date and that was setted in this way elsewhere in my code:
qsTir.setDataRiferimentoNav(new Date().toString());
So, what is wrong? What am I missing? How can I solve this issue and correctly perform my query?
You need to proper format the date to be understood by the database:
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatted = formatter.format(qsTir.getDataRiferimentoNav());
Ideally, you should avoid concatenating SQL as this can lead you to SQL injection vulnerabilities. Try to use parameterized queries to achieve your goal.

I need help selecting within a MySQL DateTime range in Java

I've got the following code in my app
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = " + userId +
" AND InsertTimestamp BETWEEN " + lastDate +
" AND " + DataProcessor.TODAY + " ORDER BY UserId, Occurred";
try{
if(null == conn)
openDatabaseConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery(); <------- this is the line which throws the SQL exception
retArray = this.getArrayListFromResultSet(rs);
}catch(SQLException sqle){
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
So when I run my app in the debugger, I get this exception message
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '00:00:00.0 AND 2014-08-20 00:00:00.0 ORDER BY UserId, Occurred' at line 1
I'm reasonably certain that there's simple and reasonable solution to this, but I have not been able to find it.
I've tried looking in the MySQL manual for a solution or a different format.
I've tried running my timestamps through a TIMESTAMP() functino and a DATE() function in the SQL, neither of which helped.
I pulled the fully formed SQL out of the Java code and ran it in MySQL Workbench with no issues, what-so-ever. So now I'm looking to the experts for help.
Dates in SQL must be enclosed within single quotes like strings.
As you're using a prepared statemtent, why you don't use '?' and stmt.setDate(...)?
String sql = "SELECT colA, colB, colC " +
"FROM " + tblName + " WHERE UserId = ?" +
" AND InsertTimestamp BETWEEN ?" +
" AND ? ORDER BY UserId, Occurred";
try {
if(null == conn) {
openDatabaseConnection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, userId);
stmt.setDate(2, lastDate);
stmt.setDate(3, DataProcessor.TODAY);
ResultSet rs = stmt.executeQuery();
retArray = this.getArrayListFromResultSet(rs);
} catch(SQLException sqle) {
JSONObject parms = new JSONObject();
eh.processSQLException(methodName, sqle, sql, parms);
}
Anyway, I think you are setting the dates in the opposite order. You should put first 'today' then lastDate. Although I don't know your constraints...

Using Timestamp in java sql prepared statement

I am trying to execute a select query using prepared statement in Java.
In Where clause im checking for a condition on Timestamp type column as shown below.
String selectSQL = "select * from db.keycontacts WHERE CREATEDDATETIME>?";
PreparedStatement preparedStatement = connect.prepareStatement(selectSQL);
preparedStatement.setTimestamp(1, convertStrToTimestamp(lastSyncTimeStamp));
resultSet = preparedStatement.executeQuery(selectSQL );
//function to convert timestampString to java.sql.Timestamp
private java.sql.Timestamp convertStrToTimestamp(String dateTimeStr){
java.sql.Timestamp timeStampDate = null;
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//2015-05-11 18:26:55
java.util.Date dateObj = (java.util.Date)formatter.parse(dateTimeStr);
timeStampDate = new Timestamp(dateObj.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return timeStampDate;
}
When the query is executed, getting following exception.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
So where exactly im going wrong here?
thanks in advance.
Remove the parameter from
resultSet = preparedStatement.executeQuery(selectSQL );
and change to
resultSet = preparedStatement.executeQuery( );
The query you passed in preparedStatement.executeQuery(selectSQL ); takes priority over the query you passed in connect.prepareStatement(selectSQL); which is the simple string ("select * from db.keycontacts WHERE CREATEDDATETIME>?") in which you dint set any parameter so there is a syntax error for ?
and you can also say that statement is prepared at PreparedStatement preparedStatement = connect.prepareStatement(selectSQL); since executeQuery() is inherited from Statement it will execute query without preparing it.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","rootpasswd");
PreparedStatement ps = con.prepareStatement("select p.PARKING_NUMBER, p.TYPE, p.AVAILABLE, "
+ "t.PARKING_NUMBER, t.VEHICLE_REG_NUMBER, t.PRICE, t.IN_TIME, t.OUT_TIME "
+ "from parking p inner join ticket t on p.PARKING_NUMBER = t.PARKING_NUMBER "
+ "where t.In_TIME = ?");
Timestamp ts = new Timestamp(BigDecimal.valueOf(expectedInTime.getTime()/1000d).setScale(0, RoundingMode.HALF_UP).longValue()*1000);
//To Round Half Up from millisecond (d for double) to second (long so no d) because MySQL do this.
ps.setTimestamp(1, ts);
ResultSet rs = ps.executeQuery();

How to get TIME out of DATETIME MySQL using java.sql.Date

I have a DATA/TIME field in my MySQL database and I'm trying to convert it to date and time in Java. The date works fine, but in time is set to null. I have tried util.Date as well but I get the same result. How can I convert a DATE/TIME to java.sql.Date without losing the time?
This is my code
try{
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT orders.id, orders.date FROM user, orders " +
"WHERE user.username='" + user.getUsername() + "' AND user.id = orders.user");
while(resultSet.next()){
Order order = new Order();
order.setId(resultSet.getInt(1));
order.setUser(user);
order.setDate(resultSet.getDate(2));
System.out.print(order.getDate());
System.out.print( " -> " + order);
orders.add(order);
}catch(SQLException ex){
System.out.println(ex);
}
try this
java.sql.Date date = new Date(resultSet.getTimestamp(2).getTime());
You are not asking this, but you could save the date as a long in mysql and just treat it as a number.
To get the date back just do a new java.util.Date(mysqllong).

How to add to a 'time' type in MySQL with JDBC?

I know how to 'SET' it, but how can I add to it? Such as...
// Add 1 minute to the current 'time' object
try {
Connection con = DriverManager.getConnection(url, user, password);
String sql = "UPDATE Table "
+ "SET 'Time Field' = 'Time Field' + ? "
+ "WHERE 'User Column' = 'Random Name'";
PreparedStatement statement = con.prepareStatement(sql);
statement.setTime(0, new Time(60000));
} catch (SQLException e) {
e.printStackTrace();
}
I'm sure I have to use the "ADDITEM(expr1,expr2)" function, but how exactly would I do so? I feel like it's not as easy as just typing it into my String.
You shouldn't pass in a Java date/time: you should use a SQL time/date literal, or a MySQL time/date function. Either way, you no longer need a "time" variable in your prepared statement:
// EXAMPLE: add 2 hours to current time
String sql =
"UPDATE Table " +
"SET 'Time Field' = 'Time Field' + DATE_ADD(NOW(), INTERVAL 2 HOUR) " +
"WHERE 'User Column' = 'Random Name'";
Here are the available MySql date/time functions:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Use PreparedStatement class. The documantation is here:
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
Use ADDTIME() function as below:
String sql = "UPDATE Table "
+ "SET 'Time Field' = ADDTIME('Time Field', ?) "
+ "WHERE 'User Column' = 'Random Name'";
Then set the param value with desired value.

Categories

Resources