My problem is that I can't fetch all records that are between two dates.
I have two JDateChoosers. When I select two dates like '10-apr-2011' to '20-apr-2011' I want all the records between those dates to be displayed in my JList. But I can't get any results in the JList.
I am using mysql database.
private void Display(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
(Connection)DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","ubuntu123");
java.util.Date jd = jDateChooser1.getDate();
java.util.Date jd1 = jDateChooser2.getDate();
// PreparedStatement stmt = (PreparedStatement) con.prepareStatement("select date from invoice where date = ?);
// PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date BETWEEN ' ' AND ' '");
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= '+jd + ' AND date <= '+jd1 + '");
pstmt.execute();
ResultSet rs = pstmt.getResultSet();
int i =0;
DefaultListModel listModel = new DefaultListModel();
while(rs.next())
{
String [] data;
data = new String[100];
data [i] = rs.getString("date");
jList1.setModel(listModel);
listModel.addElement(data [i]);
i = i+1;
}
}
catch (Exception e)
{
System.out.println("2nd catch " + e);
}
}
Can anyone tell me where my mistake is?
Thanks in advance..
Since this is a PreparedStatement you can try:
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= ? AND date <= ?");
pstmt.setDate(1,new java.sql.Date(jd.getTime()));
pstmt.setDate(2,new java.sql.Date(jd1.getTime()));
ResultSet rs = pstmt.executeQuery();
You need to take out jList1.setModel(listModel); out of the loop
while(rs.next())
{
String [] data;
data = new String[100];
data [i] = rs.getString("date");
//jList1.setModel(listModel);
listModel.addElement(data [i]);
i = i+1;
}
jList1.setModel(listModel);
You need to alter your query. Something like this:-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String jdStr = sdf.format(jd);
String jd1Str = sdf.format(jd1);
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= '" + jdStr + "' AND date <= '" + jd1Str + "'");
Previously, in your query, the 2 parameters, jd & jd1 were not getting append. This change will now append it in the query. The problem was with the jd & jd1 not correctly being appended in the query.
Note:- I've added a SDF so that you could format your date in format needed and append it to the query.
never to create an GUI Objects inside hard and long running JDBC, nor inside try - catch - finally, on exception those Object never will be created
DefaultListModel listModel = new DefaultListModel(); should be created an local variable, and then isn't required to recreate a new XxxListModel on runtime
have to remove all elements from listModel, otherwise new Items will be appended to the end of JList
definition for String [] data; and data = new String[100]; and data [i] = rs.getString("date"); inside while(rs.next()) { are quite useless, because database records are stored from this array in XxxListModel, and accessible for other usage for elsewhere
Connection, PreparedStatement and ResultSet should be closed in finally block (try - catch - finally), otheriwe these Objects stays (and increasing) in JVM memory,
are you sure dates in SQL and date from java.util.Date are in the same format?
Try using
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
to check whenever they are same.
jd and jd1 by default would differ by SQL date #see SQL Dates
This is not the correct way of using PreparedStatement, which is already prepared to handle Dates, so you should not covert them to String. Your code should look like this:
PreparedStatement pstmt = ...
pstmt.setDate(...)
Also your query String is not really using the jd as a variable, you misused ' and "
Related
I have a java program that reads the date as string from an input file and updates the Oracle table, where this date is part of an index fields.
I tried the following options:
a) Reading the data from csv file delimited by ; as String
109920541;2013-01-17 11:48:09;EDWARD ANTHONY;
b) Using SimpleDateFormat convert String to Date in a routine:
java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dt = formatter.parse("2013-01-17 11:48:09");
c) Use this date to prepare my sql stmt:
String update_query = "UPDATE "+ tableName +" SET NAME = ? WHERE ID = ? AND DATE_TIME = ?";
java.sql.Connection conn = java.sql.DriverManager.getConnection(dbUrl, dbUser, dbPwd);
java.sql.PreparedStatement pstmt = conn.prepareStatement(update_query);
if (dt not null) {
pstmt.setObject(1, new java.sql.Timestamp(dt.getTime()),java.sql.Types.DATE);
}
pstmt.executeBatch();
d) This does not find the date which is a part of key and so the data is not updated.
In sql developer I use the below query to fetch row:
SELECT * FROM table
WHERE ID = '1099205410'
AND DATE_TIME = TO_DATE('2013-01-17 11:48:09', 'YYYY-MM-DD HH24:MI:SS');
How to convert a java String to Oracle date?
Thanks.
For a single line:
pstmt.setString(1, name);
pstmt.setInt(2 id);
pstmt.setTimeStamp(3, ew java.sql.Timestamp(dt.getTime()));
pstmt.executeUpdate();
If the DATE_TIME value is not always present in the CSV data, simply use a second PreparedStatement; with just 2 parameters.
If you are using a loop reading the lines, do
for ... {
...
pstmt.clearParameters();
pstmt.setString(1, name);
pstmt.setInt(2 id);
pstmt.setTimeStamp(3, new java.sql.Timestamp(dt.getTime()));
pstmt.addBatch();
}
pstmt.executeBatch();
You might consider using the new time APIs.
(UPDATE is for existing records.)
I have to check the rooms available during a particular period ie from a starting date to an ending one for a hotel reservation system. To choose a starting and ending date, I used a JCalendar. The problem is that I am getting an error when I am creating the SQL string query and also I don't know how to retrieve the date from the JCalendar to be used in the query.
Below are code snippets of what I have done and where I am stucked.
JCalendar instantiation:
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
Query to check for rooms available:
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/testing?autoReconnect=true&useSSL=false";
String connectionUser = "root";
String connectionPassword = "admin";
conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
stmt = conn.createStatement();
String query = "select * from testing.room as ro
where ro.room_id not in
(
select re.room_no
from testing.booking as re
where (arrival_date >= "2016-05-24" and departure_date < "2016-05-29")
or (departure_date >= "2016-05-24" and arrival_date < "2016-05-29")
)";
rs = (ResultSet) stmt.executeQuery("");
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getString(2)
+ " " + rs.getString(3)+ " " + rs.getString(4)+ " "+ rs.getString(5));
}
} catch (Exception e) {
e.printStackTrace();
}
I have hardcoded the dates here :
where (arrival_date >= "2016-05-24" and departure_date < "2016-05-29")
or (departure_date >= "2016-05-24" and arrival_date < "2016-05-29")
That's because I don't know how to take the values from the JCalendar to write it there ie should I use PreparedStatements and get the text or something?
And also, I am getting an error with the query ie where I wrote String query= "query" as it says "Insert missing quotes".
You need to make two changes here:
Get the dates from JDateChooser fields (by calling getDate() method on JDateChooser objects).
Use PreparedStatement and set the dates dynamically. Below is an exmple:
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
PreparedStatement pStmt = conn.prepareStatement("select * from testing.room where arrival_date >= ? and departure_date < ?");
pStmt.setDate(1, arrival.getDate());
pStmt.setDate(2, departure.getDate());
ResultSet rs = preparedStatement.executeQuery();
I am trying to solve a problem of my code. In the following code, it contains JComboBox which have a list of month. When I click on January, I want to show all the details of that month.
private void jComboBox1_MonthsActionPerformed(java.awt.event.ActionEvent evt) {
String selection = (String)jComboBox1_Months.getSelectedItem();
if(selection.equals("January")){
try{
String sql = "select * from booking where Date = ??/01/??"; //problem
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
viewBookingTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
}
}
}
The format for the Date is 12/01/16 in the Database with type CHAR.
Please help. Thank you very much in advance.
Even though I suggest revisiting your aprroach and favor the usage of the java.sql.Date type, you can select the desired rows using a LIKE predicate:
String sql = "SELECT * FROM booking WHERE Date LIKE '%/01/%'";
Yo could do that:
String sql = "select * from booking where SUBSTR(Date,4,2) = "01";
int index = jComboBox1_Months.getSelectedIndex() + 1;
String sql = "SELECT * FROM `booking` WHERE `date` like '%?%';
pst = conn.prepareStatement(sql);
pst.setObject(1, index);
...
Relatively new to using database and for some reason I can't get this 'execute' to work.
statment2.execute("insert into table Value (" + int + "," + date + "," + int + ",'" + string + "')");
The error I get is "missing a comma". The date is designated as dates only in that particular field.
I set it up as follows
Date date = new Date();
date.setMonth(month);
date.setYear(year);
date.setDate(weekStart); //weekStart is always monday
Do I need to use just plain old date or date.toString? I was going to use Calendar but I don't know how to set a DB date using the Calendar object. I didn't see a "gety/m/d" method.
So, is the problem my query or am I improperly using the Date object to set the date in the database?
Edit:
Tried the response, got incorrect format - Expected Date got number.
Tried
sqlDate.valueOf(dateString I created)
sqlDate.toString()
sqlDate
Using a preparedStatement wouldn't fix this would it? I realize it's supposed to be better for security reasons.
First, you should use a PreparedStatement to insert values in your query. This has many advantages including avoiding SQL Injection issues. If you use PreparedStatement, you will be avoid the errors that you are seeing now. Your code using PreparedStatement would something like this:
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "insert into table (column1,column2,column3,column4) values(?, ?, ?,?)";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, 1);
pstmt.setDate(2, sqlDate);
pstmt.setInt(3, 3);
pstmt.setString(3, "test");
pstmt.executeUpdate();
} catch (Exception e) {
//log the error messages log.error(e,e);
//throw the actual exception upstream
} finally {
pstmt.close();
conn.close();
}
I am not sure what you meant by "DB" date. If you are after the sql date object you can convert a java.util.Date object to a java.sql.Date object this way:
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
I am using ms access DB. I need to obtain sale by date.
Here is my table specification:
BILL_NO DATE SALE
1 8/30/2010 1000
2 8/30/2010 2000
3 8/31/2010 3000
4 8/31/2010 2000
If i want the sale for 8/31/2010 it should return 5000.
I have inserted Date values using java.sql.Date object in DB.
Noted should be that DATE is a reserved keyword in MS Access. You need to specify it with braces. Further, you'd like to use SimpleDateFormat to convert a human readable date string to a fullworthy java.util.Date object which you in turn can construct a java.sql.Date with which in turn can be set in the PreparedStatement the usual way.
Here's a kickoff:
String sql = "SELECT SUM(SALE) as TOTAL_SALE FROM tbl WHERE [DATE] = ? GROUP BY [DATE]";
java.util.Date date = new SimpleDateFormat("MM/dd/yyyy").parse("8/31/2010");
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
int totalSale = 0;
try {
connection = database.getConnection();
statement = connection.prepareStatement(sql);
statement.setDate(new java.sql.Date(date.getTime());
resultSet = statement.executeQuery();
if (resultSet.next()) {
totalSale = resultSet.getInt("TOTAL_SALE");
}
} finally {
close(connection, statement, resultSet);
}
select
sum(SALE) as TOTAL_SALE
from
tbl
where
DATE='8/31/2010'
group by
DATE
Select sum(SALE) from [your table name] where Format([DATE],"mm/dd/yyyy")='08/30/2010';