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.)
Related
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.
I am trying to write a query in my Java program to select records between two dates. I have built my dates as such:
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy", Locale.ENGLISH);
Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
When I query the DB I get the attached.
I cannot get the query to select any records (e.g. between 01/01/15 and 12/31/15). I have tried all sorts of combos of strftime, but to no avail.
I am a noob to Java and SQLite, so I am sure it is a dumb user error.
Sorry about my reply below.
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '01/01/15' AND '12/31/15'
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '2015/01/01' AND '2015/12/31'
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '2015-01-01' AND '2015-12-31'
SELECT Course, date DateSort FROM Peter_SCORE_TBL strftime('%m/%d/%Y', DateSort) BETWEEN '01/01/15' AND '12/31/15'
Above is what I have tried in Firefox SQLite Manager extension.
EDIT:
In the above, I had DateSort defined as DATETIME. I have changed to DATE and VARCHAR and run the above queries, nothing selected.
I have also tried:
SELECT * FROM Peter_SCORE_TBL WHERE date(DateSort) BETWEEN date('01/01/15') AND date('12/31/15')
SELECT * FROM Peter_SCORE_TBL WHERE date(DateSort) BETWEEN date('2015-01-01') AND date('2015-12-31')
Neither worked. Don't know what else to try.
EDIT:
I grabbed this small piece of code and modified it to test. It does not work. What am I missing?
public class SQLiteTest
{
public static void main(String[] args) throws Exception
{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:/Users/peterream/Desktop/Desktop Archive/Crashplan/sqlitetest.sqlite");
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists people;");
stat.executeUpdate("create table people (name TEXT, occupation TEXT, DateSort INTEGER);");
PreparedStatement prep = conn.prepareStatement(
"insert into people values (?, ?, ?);");
prep.setString(1, "Gandhi");
prep.setString(2, "politics");
prep.setDate(3, convertSQLDate("2016-04-08"));
prep.addBatch();
prep.setString(1, "Turing");
prep.setString(2, "computers");
prep.setDate(3, convertSQLDate("2015-04-08"));
prep.addBatch();
prep.setString(1, "Wittgenstein");
prep.setString(2, "smartypants");
prep.setDate(3, convertSQLDate("2014-04-08"));
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);
ResultSet rs = stat.executeQuery("select * from people WHERE strftime('%Y-%m-%d', DateSort) BETWEEN '2015-01-01' AND '2015-12-31';");
while (rs.next()) {
System.out.println("name = " + rs.getString("name"));
System.out.println("job = " + rs.getString("occupation"));
System.out.println("DateSort = " + rs.getString("DateSort"));
}
rs.close();
conn.close();
}
/**
**
* This method converts input string date to sql date format
*
* #param String sqlDateIn (MM/dd/yy)
* #return java.sql.Date returnDate
*/
public static java.sql.Date convertSQLDate (String sqlDateIn)
{
java.sql.Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
java.util.Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
catch (ParseException e)
{
e.printStackTrace();
}
return returnDate;
}
}
I am looking to select 1 row 2015-04-08.
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 "
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';