How to obtain sale by date in java? - 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';

Related

org.postgresql.util.PSQLException: ERROR: column is of type date but expression is of type integer: cannot write date into postgres using java

I'm trying to insert a record inside my table but I cannot insert any values into the Date column.
This is the code I use to make an insert:
Connection connection = DatabaseConnection.getInstance().getConnection();
ResultSet result = null;
try
{
Statement statement = connection.createStatement();
statement.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
result = statement.getGeneratedKeys();
} catch (SQLException e)
{
e.printStackTrace();
}
finally
{
return result;
}
How I call this function:
String authorName = "Paul"
String authorSurname = "Mac"
DateTimeFormatter f = DateTimeFormatter.ofPattern( "yyyy-MM-dd" ) ;
LocalDate date = LocalDate.parse ( "2017-09-24" , f );
"Insert into autore(nome_autore, cognome_autore, datanascita) values('"+authorName+"', '"+authorSurname+"', "+date+")")
The fullstack trace I get:
org.postgresql.util.PSQLException: ERROR: column "datanascita" is of type date but expression is of type integer
Suggerimento: You will need to rewrite or cast the expression.
Posizione: 90
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2676)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2366)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:356)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:496)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:413)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:333)
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:319)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:1259)
at org.postgresql.jdbc.PgStatement.executeUpdate(PgStatement.java:1240)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.DatabaseConnection.QueryManager.executeUpdateWithResultSet(QueryManager.java:113)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.DAOImplementation.AuthorDaoPostgresql.insertAuthor(AuthorDaoPostgresql.java:136)
at projectRiferimentiBibliografici/com.ProjectRiferimentiBibliografici.Main.MainCe.main(MainCe.java:43)
The correct solution to this problem is to use a PreparedStatement - do not concatenate parameters into SQL strings.
Your problem with the date parameter is only the tip of the iceberg.
The next problem you'll get is, if Peter O'Donnel signs up.
So you should use something like this:
String authorName = "Paul";
String authorSurname = "Mac";
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse("2017-09-24", f);
String insert = "Insert into autore(nome_autore, cognome_autore, datanascita) values(?,?,?)";
PreparedStatement pstmt = connection.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, authorName);
pstmt.setString(2, authorSurname);
pstmt.setObject(3, date, java.sql.Types.DATE);
pstmt.executeUpdate();
There is a way to solve this. In the place Where is you specify the jdbc url.
Ex:
"jdbc:postgresql://host/schema"
Change above to
"jdbc:postgresql://host/schema?stringtype=unspecified"
Then your db determine type of your params not the jdbc driver.
Here you are using direct insert sql statement. As you are appending date object to string it will be converted to date.toString() which might not be expected format in sql.
Below is the insert sql statement:
"Insert into autore(nome_autore, cognome_autore, datanascita)
values('"+authorName+"', '"+authorSurname+"', '2017-09-24')")
Note: This approach of sql query building is not recommended and open to SQL Injection. Better to use PreparedStatement or an ORM framework.

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

Calling a MSSQL stored procedure in Java

I have access to a stored procedure on a sql server which has one parameter and I can easily run it on the sql client as follow:
exec sp_name "2016/11/01"
Now I want to do the same thing in java.
PreparedStatement ps = conn.prepareStatement("sp_name ?");
ps.setString(1, "2016/11/01");
ResultSet rs = ps.executeQuery();
In rs I can see the columns' names, but zero row is returned. I think it is because of the stored procedure's parameter. Am I missing something here?
Here is the code that worked eventually:
String date= "2016/11/01"
String queryString "exec sp_dmp_pub_status ?";
PreparedStatement ps = conn.prepareStatement(queryString);
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date parsed = format.parse(date);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
ps.setDate(1, sqlDate);
ResultSet rs = ps.executeQuery();

Single quote missing in query

i am passing date in sql query using java.Below is my code that retrieve no result.
java.sql.Date d1=java.sql.Date.valueOf(startDate);
java.sql.Date d2=java.sql.Date.valueOf(enddate);
String url= "jdbc:jtds:sqlserver://"+serverName+"/"+database;;
String driver = "net.sourceforge.jtds.jdbc.Driver";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
System.out.println("Connected to the database!!! Getting table list...");
Statement sta = conn.createStatement();
String Sql = "Select INDEX from Table where DATE between "+d1+" and "+d2;
System.out.println("sql="+Sql);
rs = sta.executeQuery(Sql);
}
} catch (Exception e) {
e.printStackTrace();}
Query returns no row because date should be passed as '2015-02-28' but query treats date as 2015-02-28 without single quote.Please suggest.
Creating SQL statements by concatenating strings together makes your software vulnerable to SQL injection (if the values of the variables come from user input).
You should use PreparedStatement instead:
PreparedStatement sta =
conn.prepareStatement("Select INDEX from Table where DATE between ? and ?");
sta.setDate(1, d1);
sta.setDate(2, d2);
rs = sta.executeQuery(Sql);
Add single quotes
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
but the best option would be using PreparedStatement.
Try it like so:
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2 + "'";
That being said, you should look into PreparedStatements.
You have multiple issues in the query
INDEX is a reserved word and you need to escape it using backticks http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Date should be used within quotes
So the query should be
String Sql = "Select `INDEX` from Table where DATE between '"+d1+"' and '"+d2+"'";
Replace Your Query with
String Sql = "Select INDEX from Table where DATE between '"+d1+"' and '"+d2+"'";
I suggest you to use PreparedStatement Instead
String query="Select INDEX from Table where DATE between ? and ?";
PreparedStatement ps=con.prepareStatement(query);
ps.setDate(1,d1);
ps.setDate(2,d2);
ps.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 "

Categories