Problems with Date, preparedStatement, JDBC and PostgreSQL - java

I Have to get a movie from a PostgreSQL database that matches a given title and release date.
title is a character(75) and releaseDate is a date. I Have this code:
String query = "SELECT * FROM \"Movie\" WHERE title = ? AND \"releaseDate\" = ?)";
Connection conn = connectionManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(query);
java.sql.Date date = new java.sql.Date(releaseDate.getTime());
stmt.setString(1, title);
stmt.setDate(2, date);
ResultSet result = stmt.executeQuery();
but it's not working because the releaseDate is not matching when it should.
The query SELECT * FROM "Movie" WHERE title = A_MOVIE AND "releaseDate" = A_DATE works perfectly on a command shell using psql

The problem was in the database because of time format was changed from dd/MM/YYYY to MM/dd/YYYY.
Thanks

Related

How to filter data by date (obtained from a JCalendar) using MySQL

I'm having a hard time trying to filter data by date
MySQL Query
public DefaultTableModel getData1(Date start,Date end){
.......
String sql = "SELECT * FROM torch.new_table WHERE pro_date between '"+start+"' and '"+end+"'";
.....
}
Code for get date from a JCalendar
DefaultTableModel dm = new Products().getData1(sDate.getDate(), eDate.getDate());
Complete code is Here: http://postimg.org/image/4zycbtj4n/
Use the wildcard '?' when you are defining the query.
Replace each wildcard using setDate and a new java.sql.Date.
...
String sql = "SELECT * FROM torch.new_table WHERE pro_date between ? and ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(start.getTime());
ps.setDate(2, new java.sql.Date(end.getTime());
ResultSet rs = ps.executeQuery();
...
If you obtain a String from a JDateChooser, you can use
ps.setDate(1, java.sql.Date.valueOf(start));
ps.setDate(2, java.sql.Date.valueOf(end));
More possibilities here Using setDate in PreparedStatement
Part of code to filter data by date (Obtained from a jCalender) using MySQL
Thanks for help #RubioRic
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//dateT and dateE type jDatechooser
String get = sdf.format(dateT.getDate());
String get1 = sdf.format(dateE.getDate());
// Query to select get data from database
String sql = "SELECT * FROM date WHERE DATE(Date) >= ? && DATE(Date) <= ?";
try{
Connection conn = dataB.mySqlCon();
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, get);
st.setString(2, get1);
ResultSet rs = st.executeQuery();

mysql: finding groups of records within a specified time period in Java

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

Update ResultSet in MySQL for DateTime column

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.

Whats the sql query for retrieving data from database between two dates, if the date values are stored on a variable?

I have been using MS access database, and i used this code to fetch records from the database on which it was working perfect. But now, as i changed my database to mysql, this piece of code is not fetching records from database. The database connections are working. The dates entered in the textbox are stored to a variable and i want to use that variables to fetch records from the database. Thanks for the help in advance.
java.util.Date StartDate=(java.util.Date)textField1.getValue();
java.util.Date EndDate=(java.util.Date)textField2.getValue();
java.sql.Date startDate = new java.sql.Date(StartDate.getTime());
java.sql.Date endDate = new java.sql.Date(EndDate.getTime());
PreparedStatement ps = conn.prepareStatement("select * from table_nm where 'Date1 BETWEEN #startDate# AND #endDate#' ");
ResultSet rs = ps.executeQuery();
while(i8rs.next())
{
Date i8Date = rs.getDate("Date1");
String i8ItemName = rs.getString("Item_Name");
int i8Quantity = rs.getInt("Quantity");
Double i8Rate = rs.getDouble("Rate");
Double i8total = rs.getDouble("Total");
Object[] row = new Object[5];
row[0] = i8Date;
row[1] = i8ItemName;
row[2] = i8Quantity;
row[3] = i8Rate;
row[4] = i8total;
tableModel.addRow(row);
}
Assuming that Date1 is the column name in your table.
Change:
PreparedStatement ps =
conn.prepareStatement("select * from table_nm
where 'Date1 BETWEEN #startDate# AND #endDate#' ");
To:
PreparedStatement ps =
conn.prepareStatement("select * from table_nm
where Date1 BETWEEN ? AND ? ");
ps.setDate( 1, startDate );
ps.setDate( 2, endDate );
Refer To:
Java: Using Prepared Statements
Just use this
PreparedStatement ps = conn.prepareStatement("select * from table_nm
where Date1 BETWEEN ? AND ? ");
ps.setDate( 1, startDate );
ps.setDate( 2, endDate );
ResultSet rs = ps.executeQuery();
while(rs.next())
{
// your table values

cannot insert java.sql.Date to the "Date" field in the database

I am getting a string value such as "2012-01-20" and converting it to sql.Date to insert it in the database.
code
java.util.Date DOB = new java.util.Date();
String datetext = txtDate.getText();
SimpleDateFormat sd = new SimpleDateFormat("yyyy-mm-dd");
DOB = sd.parse(datetext);
java.sql.Date sqlDate = new java.sql.Date(DOB.getTime());
String query = "ISERT INTO EMPLOYEE ('DOB')"
+ " VALUES ( ? ) ";
con = db.createConnection();
try{
ps = con.prepareStatement(query);
ps.setDate(1, sqlDate);
ps.executeQuery();
}catch(Exception ex){
System.err.print(ex);
}
When i run this code I am getting an exception ""[Microsoft][ODBC SQL Server Driver]Optional feature not implemented"
what am i doing wrong here ? pls help !
Remove single quote - ('DOB') and INSERT (misspell)
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
You may use java.sql.Date.valueOf("2012-01-20") method to convert string to sql date.
Use executeUpdate() method instead of executeQuery().
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
con = db.createConnection();
try{
ps = con.prepareStatement(query);
ps.setDate(1, java.sql.Date.valueOf("2012-01-20"));
//Or use
// ps.setTimestamp(1, new Timestamp(DOB.getTime()));
ps.executeUpdate();
}catch(Exception ex){
System.err.print(ex);
}

Categories

Resources