PreparedStatement.setTimestamp is not inserting Timestamp into DB - java

I am working on account management system. Goal is to set trial period into db. I am getting Timestamp "2015-10-30 22:55:48" from jsonObject into REST service and inserting into db using prepared statements. But each time I am getting effected rows 0 and means update operation is not performed!
I have tried following piece of code including parsing and conversion:
JSONParser parser = new JSONParser();
Object obj = parser.parse(requestBody);
JSONObject jsonObject = (JSONObject) obj;
String accountExpiryStr = jsonObject.get("accountExpiry").toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parsedDate = dateFormat.parse(accountExpiryStr);
Timestamp accountExpiry = new Timestamp(parsedDate.getTime()); // accountExpiry output is 2015-10-30 22:55:48.0
String requestQuery = "UPDATE table SET Account_Expiry = ?"
+ "WHERE Account_Id = ? "
+ "AND User_Id = ? ";
preparedStatement = con.prepareStatement(requestQuery);
preparedStatement.setTimestamp(1, accountExpiry);
preparedStatement.setInt(2, Integer.parseInt((String) jsonObject.get("selectedUserId")));
preparedStatement.setInt(3, Integer.parseInt((String) jsonObject.get("accountId")));
rowCount = preparedStatement.executeUpdate();
System.out.println("Effected Rows: " + rowCount);

Affected rows = 0 means that the where clause of the UPDATE did not match any record in your table. So you should first check if the where clause is correct.
Seems you have switched user id and account id...
Instead write:
preparedStatement.setInt(2, Integer.parseInt((String) jsonObject.get("accountId")));
preparedStatement.setInt(3, Integer.parseInt((String) jsonObject.get("selectedUserId")));

Related

Oracle: convert java date to Oracle date in java program

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.)

IF Statement using SQL data to set variable

I'm currently writing a java application which is used to print bar codes out, which the information for is obtained from a MySQL database. The data in SQL has a property which defines which type of bar code it is, value 1 = serialized and 2 = un-serialized. I was wondering how I would use an if statement to set a variable to define what type of bar-code is being used - in java.
On the SQL database the value for bar code type is 'FK_BarcodeTypeID'
The code I have so far is:
String SQL ="SELECT [PK_PrintQueueID]" +
" ,[FK_PrinterID]" +
" ,[FK_BarcodeTypeID]" +
" ,[Barcode]" +
" ,[Quantity]" +
" ,[QueueDate]" +
" ,[ProcessedDate]" +
" FROM [Brad].[dbo].[PrintQueue]" +
" WHERE ProcessedDate IS NULL";
//Declare variable connection.
Connection connection = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
// System.out.println(dateFormat.format(date));
//
try {
connection = DriverManager.getConnection(connectionString);
Statement stmt = connection.createStatement();
Statement stmt2 = null;
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("Barcode"));
// System.out.println(rs.getString("PK_PrintQueueID"));
// System.out.println(rs.getString("ProcessedDate"));
String SQL2 = "UPDATE PrintQueue SET ProcessedDate = '"+dateFormat.format(date)+"' WHERE PK_PrintQueueID = '"+rs.getString("PK_PrintQueueID")+"' ";
// System.out.println(SQL2);
String ZPL = "^XA ^FX BARCODE ^BY4,2,050 ^FO140,40^BC^FD"+rs.getString("Barcode")+"^FS ^XZ";
System.out.println(ZPL);
// THIS IF STATEMENT SETS TYPE OF BARCODE TO
// TYPE 1 OR 2
I tried using the following but had no luck;
String BCSerialized = "SELECT * FROM PrintQueue WHERE FK_BarcodeTypeID = '1'";
System.out.println(BCSerialized);
String BCUnSerialized = "SELECT * FROM PrintQueue WHERE FK_BarcodeTypeID = '2'";
System.out.println(BCUnSerialized);
I am struggling to work out how to do the above, therefore any advice is appriciated.
Thankyou!

Using a complex sql query to check availability of date/room using JCalendar

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();

Cant get records between two dates

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 "

How to obtain sale by date in java?

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';

Categories