I have a database whose one table (query_user) has 4 columns out of which 2 (access_time, answer_time) are of timestamp (e.g. 2011-08-11 01:18:41.712) type.
I want to query on that table, such as follows:
String query="select access_time from query_user where access_time between ? and ?";
Now in my java code:
PreparedStatement ps = null;
Connection con = DBConnectionManager.getConnection();
ps = con.prepareStatement(query);
ps.setString(1,"2011-08-11 01:18:41.712");
ps.setString(2,"2011-09-11 01:18:41.712");
I'm not sure about what should I use at ps.setDate() or ps.setString() or ps.setInt()?
Any help?
use ps.setDate() as the database column is datetime
Use ps.setString() method in database that string treated as DateTime or timestamp type.dont worry..
Related
I want to link the mysql database using Java, execute query returns the record of the specified period, and finally present the result in form of table in java.
How can I convert the input string into the mysql valid date and output the result?
I tried this, but failed.
Connection con = DBCon.dbcon();
java.util.Date t1= new SimpleDateFormat("yyyyMMdd").parse(jTextField2.getText());
java.util.Date t2= new SimpleDateFormat("yyyyMMdd").parse(jTextField3.getText());
PreparedStatement query = con.prepareStatement(SELECT * FROM transaction WHERE TransactionDate >= ? and TransactionDate <= '"+t1+"' and id1=?);
ResultSet rs = query.executeQuery();
Thank you very much!!!
You have to set parameters to PreparedStatement instance as follows:
Connection con = DBCon.dbcon();
java.util.Date t1= new SimpleDateFormat("yyyyMMdd").parse(jTextField2.getText());
java.util.Date t2= new SimpleDateFormat("yyyyMMdd").parse(jTextField3.getText());
PreparedStatement query = con.prepareStatement(SELECT * FROM transaction WHERE TransactionDate >= ? AND TransactionDate <= ? AND id1 = ?);
query.setDate(1,new java.sql.Date(t1.getTime()));
query.setDate(2,new java.sql.Date(t2.getTime()));
query.setLong(3,id);// Assuming Datatype of Id to Long and value in variable id, Change accordingly if not.
ResultSet rs = query.executeQuery();
Edit : Changed datatype of setDate from java.util.Date to java.sql.Date
I have a database where I have a field that is type DATE and I want to make a function in java to insert values in the database.
The problem is that when I insert a Date I get a NULL in the database DATE field.
I'm doing this:
PreparedStatement stmt = null:
stmt = conn.prepareStatement("INSERT INTO DB1(print_date) values(?)";
stmt.setDate(1, database.getPrintDate());
stmt.executeUpdate();
How can I insert the PrintDate which is DATE type in the database? Thank you
Have a problem search between 2 date
my sql statement in java
String sql ="Select * from Payment where Payment_Date between '"+date_1+"' and '"+date_2+"'";
It give me data type mismatch, I guess my problem occur in '"+date_1+"' and '"+date_2+"' ??
date_1 and date_2 I get from
Date date_1 = date1.getDate();
Date date_2 = date2.getDate();
Start using a PreparedStatement , it will prevent SQL injections . Read this SO Q&A for more.
You can do something like this :
String sql ="Select * from Payment where Payment_Date between ? and ? ";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setDate(1, date_1 );
pstmt.setDate(2, date_2 );
// date_1 and date_2 objects should be of type java.sql.Date
Make sure you set the correct parameter types in the setXXX() methods. Remember if the data type for Payment_Date is DATE and related types, you need to set java.sql.Date in the setDate() method. If the data type of column is TIMESTAMP, then use java.sql.Timestamp and setTimestamp() method.
Footnote :-
If you have a java.util.Date object with you , you can convert that to java.sql.Date as :
java.sql.Date sqlDateObject = new java.sql.Date(utilDateObject.getTime());
Package of Date class must be java.sql not java.util.
pstmt = conn.prepareStatement("Select * from Payment where Payment_Date between ? and ?");
pstmt.setDate(1, date_1);
pstmt.setDate(2, date_2);
I am executing the select statement with using jdbc sybase driver (jconn3). I checked the statement with executed manually on isql and all rows returned correctly. The statement which is executing on jdbc :
select * from mytable where date between ? and ?
I added the dateformat as yyyy-MM-dd HH:mm:ss and set the time value as 00:00:00 for begin date and 23:59:59 for end date.
It is not working. The row count must be 1000 but it is sometimes 770, sometimes 990, sometimes 564 etc.. There is no any specific row count which everytime returned.
After that I added an extra execution which returns only row count. First I am executing the select count(*) from ... statement then executing select * from .... and now `select * from ... query returns the correct number of records everytime. This can not be related with caching. And weird thing is , I am using same preparedstatement and resultset objects for those two execution.
Any idea on that issue?
#Rulmeq, here is the code (added on 2012-03-29)
ResultSet rs = null;
PreparedStatement ps = null;
ps = myConn.getConnection().prepareStatement("select count(*) from myTable where date between ? and ?");
ps.setDate(1, new java.sql.Date(beginDate.getTime())); // format : yyyy-MM-dd
ps.setDate(2, new java.sql.Date(endDate.getTime())); // format : yyyy-MM-dd
rs = ps.executeQuery();
rs.next();
// some logs here
ps = myConn.getConnection().prepareStatement("select * from myTable where date between ? and ?");
ps.setTimestamp(1, new java.sql.Timestamp(beginDate.getTime())); // format : yyyy-MM-dd hh:mm:ss
ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime())); // format : yyyy-MM-dd hh:mm:ss
rs = ps.executeQuery();
while(rs.next()){
........
}
What I think the problem is the code you are using to assign datetime values to the query arguments. And now as you specified that the code with "select * from ..." is working fine, so i think the only difference between them is that you can use
ps = myConn.getConnection().prepareStatement("select Count(*) from myTable where date between ? and ?");
ps.setTimestamp(1, new java.sql.Timestamp(beginDate.getTime()));
ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));
rs = ps.executeQuery();
for "select Count(*) from .."
Is date defined as date, datetime, smalldatetime or timestamp in myTable? You are using setDate and setTimestamp. One of them doesn't match the date type defined in myTable.
In Oracle TO_DATE function would help like below.
"select count(*) from myTable where date between TO_DATE(?, 'yyyy-mm-dd') and TO_DATE(?, 'yyyy-mm-dd')"
Thanks for all but issue has been solved and it was not related with jdbc. It was related with using System.currentTimeMillis() and host system is too fast. That's why system sometime uses the same ms. I changed the references.
I am having a textbox field in my jsp called "req_date". The user is selecting a date from a javascript calendar in the format of "DD-MON-YY" ex. "29-aug-2010".So, now I am stuck while trying to insert it in the DB.
I tried " String queryString = "INSERT INTO Charity (req_date) VALUES (?)", but it is not inserting. How do I solve tis out.
The req_date is type of date in the DB.
Can you please help
Date format depends upon Database you use.
For reference Date formats with Oracle.
so your query should look like :
String queryString = "INSERT INTO Charity (req_date) VALUES (to_date('29-aug-2010', 'dd-mon-yyyy'))"
This is just to answer your question. But I will prefer usage of PreparedStatement as also suggested in other answers.
Your code using PreparedStatement should look something like following: (NOTE: I have not tested this code )
String formatIn = "dd-MMM-yyyy";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-Aug-2010");
java.sql.Date sqlDate = new java.sql.Date(inDate.getTime());
PreparedStatement prest = con
.prepareStatement("INSERT INTO Charity (req_date) VALUES (?)");
prest.setDate(1, sqlDate);
int row = prest.executeUpdate();
Use a PreparedStatement and its setDate(..). Or use a timestamp (long).
It depends on your database, PostgreSQL does recognize this format:
SELECT CAST('29-aug-2010' AS date);
Result:
'2010-08-29'
In most cases, you'd better use the ISO-format yyyy-mm-dd.