I have a table where I have to do a SELECT ... BETWEEN start_date AND end_date, as well as insert Date values into the same table.
I read things like:
java.util.Date now = new java.util.Date();
pStmt.setDate( 1, new java.sql.Date( now.getTime() ) );
pStmt.setTimestamp( 2, new java.sql.Timestamp( now.getTime() ) );
pStmt.executeUpdate();
But that kind of code sets or gets the current date, doesn't it? I want to insert and select custom dates myself.
I also read it here at StackOverflow:
SELECT *
FROM myTable
WHERE ( YEAR(myfield) = '2009')
AND ( MONTH(myfield) = '1')
Is it also possible to make the Date fields String, then use StringTokenizer to extract only the day, month or year information and use them in a SELECT similar to this code? (In case my first - and simpler - idea is impossible.)
So until now, there's two possible solutions. I also need to know which one is faster since the database accessed is in a fail-safe / critical system (a bank) with lots of data.
The first approach is better, because you were able to use date functions to manipulate values.
private void executeQuery(java.util.Date startDate, java.util.Date endDate) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select ... between ? and ?";
pstmt = conn.prepareStatement(query);
pstmt.setDate(1, new java.sql.Date(startDate.getTime()));
pstmt.setDate(2, new java.sql.Date(endDate.getTime()));
//return results
ResultSet rs = pstmt.executeQuery();
rs.last();
System.out.println("last row = " + rs.getRow());
} finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
}
Related
I want to sort sql results with a date that i get from jDateChooser and display all the returned results. This is what i have done so far. So far I have only managed to get 1 result even if i looped the sorted sql results.
public void MonthlyTotalExpenses_Report(){
String typeOfReport = (String) report_type.getSelectedItem();
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText();
db databaseCon = new db();
Connection dbconnect = db.dbconnect();
if(typeOfReport == "Total expenses"){
String selectQuery = "select name,type,sum(amount),date_payed from expenses order by ? DESC";
try{
Connection con = databaseCon.dbconnect();
ResultSet rs = null;
PreparedStatement pst = null;
pst = con.prepareStatement(selectQuery);
pst.setString(1,reportDate);
rs = pst.executeQuery();
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
for(String result : results) {
System.out.println(result);
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I want sort the results like this (for example -> 2017-01-01 to the date user select with jDateChooser) and print all the records available within that period. I just figured the sql query i wrote is wrong. It only prints the 1st value of the name column in the database. Help me to figure out how to sort according what i have mentioned above and print all the results that returned.
You might want to set the date in the where condition in your query.
select name,type,sum(amount),date_payed from expenses where date_payed = ? order by 4 DESC
Consider obtaining Date from String.
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText(); // "2017-01-01"
DateFormat format = new SimpleDateFormat("YYYY-MM-DD", Locale.ENGLISH);
Date date = format.parse(reportDate);
Then set your param with
pst.setDate(1,reportDate);
So i have this query using DATEDIFF function on MS SQL Server?
SELECT DATEDIFF(DAY,(select StartDate from CarOrder where OrderID= 59),(select EndDate from CarOrder where OrderID= 59))
This work fine and the result is 10 but i dont know how to get the return value and use it in this function for java
public int getDateDiff(int OrderID){
Connection conn = DBConnection.getConnection();
int datediff;
String getdiffSQL = "SELECT DATEDIFF(DAY,(select StartDate from CarOrder where OrderID = ? ) ,(select EndDate from CarOrder where OrderID= ?) )";
try {
PreparedStatement pstm = conn.prepareStatement(getdiffSQL);
pstm.setInt(1, OrderID);
pstm.setInt(2, OrderID);
int nRows = pstm.executeUpdate();
return nRows;
} catch (SQLException ex) {
System.out.println("Error: " + ex.getMessage());
} finally {
DBConnection.closeConnection(conn);
}
}
i want it to return the date diff number so that it is a variable i can use in java, how can i do this ?
Thank You.
Use ResultSet
You need to capture the ResultSet, and access the rows of that ResultSet (in this case a single row). If you are executing a query, call executeQuery on your PreparedStatement, thereby producing a ResultSet.
Use the modern try-with-resources syntax to automatically close your database resources. You can drop the finally clauses; no need to call closeXXX on your database resources as that chore is handled for you.
I have not tried executing the following code example, but I hope it is close to what you need. I am using the alternate SELECT line suggested in comment by Martin Smith; I’ve not put thought into that as it is not the core of your Question.
String sql = "SELECT DATEDIFF( DAY , StartDate , EndDate ) FROM CarOrder WHERE OrderID = ? ;" ;
Integer diff = null ;
try (
Connection conn = myDataSource.getConnection() ;
PreparedStatement pstmt = conn.prepareStatement ( sql ) ;
) {
pstmt.setInt( 1 , orderId ) ;
try (
ResultSet rs = pstmt.executeQuery( sql ) ;
) {
while ( rs.next ( ) ) {
diff = rs.getInt( 1 ) ; // Auto-boxing `int` to `Integer`.
}
}
}
} catch ( SQLException e ) {
e.printStackTrace ( ); // Handle error condition however you see fit.
}
if( null == diff ) {
System.out.println( "mission failed." ) ;
} else {
System.out.println( "mission succeeded. Diff is: " + diff ) ;
}
For real work, I would also test to make sure I had only one row returned (make sure that while loop runs exactly once rather than zero or more than once).
If this is not clear to you about the various database resources (DataSource, Connection, PreparedStatement, ResultSet), you should put down the IDE and do some more study of the Oracle Tutorial on JDBC matters, and do some searching/studying of Stack Overflow on the topic.
Store the result of the query in the ResultSet object, and then pick the value of the appropriate column by using of {YOUR_RESULT_SET}.getYourDataType(columnNumber).
i'm having an exam in a couple of days and there's a sample exam with a code:
import java.sql.*;
public class UpdateCar {
public static void UpdateCarNum(int carNo, int empNo) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try { con = DriverManager.getConnection( "jdbc:default:connection");
pstmt = con.prepareStatement( "UPDATE EMPLOYEES " + "SET CAR_NUMBER = ? " + "WHERE EMPLOYEE_NUMBER = " + empNo);
pstmt.setInt(2, empNo);
pstmt.executeUpdate();
}
finally {
if (pstmt != null) pstmt.close();
}
}
}
So the question is what returns an error in this code with connection to the database and bring out two ways how to improve the connection safety.
It returns an error because pstmt.setInt(2,empNo) is not defined, it should be pstmt.setInt(1,carNo).
And one way to improve safety would be to set all values in query with setInt not with variable empNo. For example
pstmt = con.prepareStatement("UPDATE EMPLOYEES "+"SET CAR NUMBER = ? "+"WHERE EMPLOYEE_NUMBER = ?");
pstmt.setInt(1,carNo);
pstmt.setInt(2,empNo);
What could i do more to improve safety (second way, thought, idea - thing requested)?
If an employee doesn't have a car then you can only set the car number to 0 or -1 but not to NULL. If you use
public static void UpdateCarNum(Integer carNo, int empNo) throws SQLException {
then you can also support this case.
If you would use String for the carNo to support this. And if you do no checks. Then someone can inject SQL and do ugly stuff if you concatenate it like in your example. Use the advantage of the prepared statement also there by putting just a ? in. Although then you can't use Integer and could use BigDecimal for carNo (because there is no pstmt.setInteger() only a pstmt.setBigDecimal()). Or alternatively use Integer and if it is null you can use pstmt.setNull() otherwise pstmt.setInt(..., carNo.intValue()).
You could also use a stringbuilder to spot this kind of error more quickly:
StringBuilder myStatement = new StringBuilder();
myStatement.append( "UPDATE EMPLOYEES" );
myStatement.append( " SET CAR_NUMBER = " + carNo );
myStatement.append( " WHERE EMPT_NO = " + emptNo );
pstmt = con.prepareStatement( myStatement.toString() );
and close you connection "con" in the finally-block
Connection is not closed. You should use try-with-resouce statement for saving resources.
try (Connection con = DriverManager.getConnection("jdbc:default:connection")) {
try (PreparedStatemt pstmt = con.prepareStatement("UPDATE EMPLOYEES SET CAR_NUMBER = ? WHERE EMPLOYEE_NUMBER = ?")) {
pstmt.setInt(1, carNo);
pstmt.setInt(2, empNo);
pstmt.executeUpdate();
}
}
I'm looking for the best way to update a DateTime field in MySQL while walking thru my result set. I have found some other questions along these lines but none that addresses the Java data and SQL date formats within a rs.updateDate statement. I have attached the code that the editor is balking at.
public class EmailQueueProcess {
public static Boolean process()
{
Date processedDtm = new Date();
java.util.Date today=new java.util.Date();
Timestamp currentTimestamp=new Timestamp(today.getTime());
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
strSQL = "select * from portal.emailqueue where portal.emailqueue.processedDtm is null";
conn = com.retailapppartners.Utils.staticGetConnection().getConnection();
stmt = conn.prepareStatement(strSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
//now loop through and update the process datetime values
rs = stmt.executeQuery();
ResultSetMetaData rsMetaData = (ResultSetMetaData) rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
while (rs.next()) {
// Grab some data then update the row
rs.updateDate ("processedDtm", currentTimestamp);
rs.updateRow();
}
} catch .....
updateDate() takes a java.sql.Date. So, I believe you have two options here,
Use rs.updateTimestamp("processedDtm", currentTimestamp);
Use java.sql.Date currentTimestamp = new java.sql.Date();
Per the MySQL Documentation in Table 5.1,
These MySQL Data Types - Can always be converted to these Java types
DATE, TIME, DATETIME, TIMESTAMP - java.lang.String, java.sql.Date, java.sql.Timestamp
So you can use either 1 or 2 above.
I have this query :
String sql ="select col1,col2,col3 from table where tstamp between '01/01/2014 00:00' and '01/01/2014 23:59'" ;
I want to use a PreparedStatement to setDate like this :
String sql = "select col1,col2,col3 from table where tstamp between ? and ? " ;
PreparedStatement p = connection.prepareStatement(sql);
p.setDate(1,..);
and I don't know how to do it..please help
I tried the new Date(int,int,int) constructor but it doesn't set the hours and minutes.
JDBC has three temporal types, all in the java.sql package:
Date, which contains a date without time
Time, which contains a time without date
Timestamp, which contains a date and a time.
You thus need to use a Timestamp, and the setTimestamp() method of PreparedStatement.
To construct a Timestamp instance from a String, use a SimpleDateFormat to parse the String into a java.util.Date object, then construct the Timestamp by passing the milliseconds obtained from this java.util.Date object.
Use java.sql.Date
try{
sql = "select col1,col2,col3 from table where tstamp between ? and ? ;
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, /**Your Date**/);
pstmt.setString(2, /**Your Date**/);
rs = pstmt.executeQuery();
.
.
.
}catch (Exception e) {
e.printStackTrace();
}finally{
sql = null;
if(rs != null){
rs.close();
rs = null;
}
if(pstmt != null){
pstmt.close();
pstmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}
For More
The problem is that the Date object from java.sql is different that the Date from java.util
Then if You use p.setDate(1,..); with a java.util.Date You will lose the time.
One possible solution could be that You passed as argument a Date from java.sql