JDBC delete rows in db with specific timestamp - java

I have a database in which I am saving messages with tiemstamps. I have table created with this code:
CREATE TABLE messages (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
msgid VARCHAR(64) UNIQUE,
payload TEXT,
sender VARCHAR(255),
cur_timestamp TIMESTAMP(3)
);
This all works perfectly. However, now I am trying to delete some rows with timestamp older than some specified by user. This is done in Java part of my system like this:
// get current timestamp
Date date = new Date();
// timestamp has to be in the same format as in database
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm:ss.SSS");
String formattedDate = sdf.format(date);
System.out.println("Current time: " + formattedDate);
// subtract desired time
if (msgOld.equals("hour")) {
date.setTime(date.getTime() - ONE_HOUR_MILLISCONDS);
formattedDate = sdf.format(date);
} else if (msgOld.equals("day")) {
date.setTime(date.getTime() - ONE_DAY_MILLISCONDS);
formattedDate = sdf.format(date);
}
This, too, works fine - the constants look like this: final long ONE_HOUR_MILLISCONDS = 60 * 60 * 1000;
The only problem is that I dont know how to write the query in JDBC. I tried doing this:
// prepare query
String query;
if (msgOld.equals("all")) {
query = "TRUNCATE TABLE messages";
} else {
query = "DELETE FROM messages WHERE cur_timestamp < " + date + ";";
}
but it says I have an error in my SQL statement (the second one, the one with TRUNCATE works fine). I tried putting formattedDate instead of date in the statement, too.
Whats wrong with it (probably something really simple - maybe difference between java.util.Date and SQL timestamp...)? Thanks for any tips!
EDIT: Thanks for all responses... I have rewritten the code so it uses prepared statement like this:
// prepare query
String query;
PreparedStatement pstmt = null;
try {
if (msgOld.equals("all")) {
query = "TRUNCATE TABLE messages";
pstmt=conn.prepareStatement(query);
} else {
query = "DELETE FROM messages WHERE cur_timestamp < ?;";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, timestamp.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
try {
pstmt.execute();
System.out.println("Successfully deleted messages.");
pstmt.close();
} catch (Exception e) {
System.out.println("Error with db query.");
e.printStackTrace();
}
but I am still getting SQL exception (even if I convert date to timestamp and like this Timestamp timestamp = new Timestamp(date.getTime()); and use it in the satement)

You cannot just concatenate java.util.Date objects into query string. That's wrong.
Better use PreparedStatement for this kind of things.
Take a look at this tutorial for example

exactly as #Funtik said preparedStatement could be used.
See this link here
it would not exactly sove your problem but you will get a clear idea.

Related

How to insert datetime in this - " 2016-01-01T19:33:15-05:00" format in MSSQL using Java?

I have an column defined as datetime(2) and I have to create a new date in this format - 2016-01-01T19:33:15-05:00
Entity: private Date transactionTime;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = null;
try {
date = formatter.parse(formatter.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
obj.transactionTime(date);
It is getting inserted in SQL as like this - "2021-08-26 14:19:09.0000000" but I need insert this in the format mentioned above.
There is only column type, datetimeoffset that can hold the timezone offset (e.g. -05:00 as mentioned in your question) value. Check the Data type mappings documentation to learn more about it.
So, if you want to store the timezone offset value, change the column type to datetimeoffset. After that, you will be able to insert the value which you have mentioned in the question.
You can use the following code to access the stored value:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT foo FROM mytable WHERE ...");
while (rs.next()) {
DateTimeOffset dateTimeOffset = rs.getObject(1, DateTimeOffset.class));
System.out.println(dateTimeOffset);
}
rs.close();
st.close();
where foo the name of the column of type, datetimeoffset.

How to resolve MySQLSyntaxErrorException in JDBC preparedStatement [duplicate]

This question already has answers here:
Variable column names using prepared statements
(7 answers)
Closed 5 years ago.
I have a query that throws a com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException and I can't figure out why. I am using xampp and when I try the same query directly, it works fine. I also have a whole bunch of other methods that use very similar queries that all work.
The problem seems to be with updating the date, I noticed in the error message that java puts ' ' around the date, which makes it a string and is probably the reason for the error. However I'm not sure how to fix this to insert the date as a date.
Here's the code:
public void update(int userId, String date, String column, String value){
try {
// convert date from String to Date
DateTime dt = DateTime.parse(date);
java.sql.Date sqlDate = new java.sql.Date(dt.getMillis());
// create prepared statement
conn = DriverManager.getConnection("jdbc:mysql://localhost/db","root", "");
String query = "UPDATE expenses_income SET ? = ? WHERE userId = ? AND date = CAST(? AS DATETIME);";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, column);
preparedStmt.setString(2, value);
preparedStmt.setInt(3, userId);
preparedStmt.setDate(4, sqlDate);
preparedStmt.executeUpdate();
conn.close();
} catch (Exception e) {
System.err.println("MySQL exception: " + e);
}
}
And the error message:
MySQL exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''comment' = '123' WHERE userId = 1 AND date = CAST('2018-01-06' AS DATETIME)' at line 1
I also tried the query without casting as datetime:
String query = "UPDATE expenses_income SET ? = ? WHERE userId = ? AND date = ?;";
But I get the same error.
I then tried to use java.util.Date instead of Joda DateTime, but it doesn't help. Any ideas?
Thanks!
.. right syntax to use near ''comment' = '123'
You are getting exception because column name parameterization, which is not correct.
UPDATE expenses_income SET ? = ?
It should be
UPDATE expenses_income SET column_name = ?
I also noticed a semicolon ; at the end of the SQL, which should be removed and you don't need to cast Date explicitly. It should be just
UPDATE expenses_income SET column_name = ? WHERE userId = ? AND date = ?
Also, you shouldn't name column name like date, it should be last_updated or something meaningful.

sort sql results and display all the results by a loop in a table in java

I want to sort sql results with a date that i get from jDateChooser and display all the returned results. This is what i have done so far. So far I have only managed to get 1 result even if i looped the sorted sql results.
public void MonthlyTotalExpenses_Report(){
String typeOfReport = (String) report_type.getSelectedItem();
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText();
db databaseCon = new db();
Connection dbconnect = db.dbconnect();
if(typeOfReport == "Total expenses"){
String selectQuery = "select name,type,sum(amount),date_payed from expenses order by ? DESC";
try{
Connection con = databaseCon.dbconnect();
ResultSet rs = null;
PreparedStatement pst = null;
pst = con.prepareStatement(selectQuery);
pst.setString(1,reportDate);
rs = pst.executeQuery();
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
for(String result : results) {
System.out.println(result);
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I want sort the results like this (for example -> 2017-01-01 to the date user select with jDateChooser) and print all the records available within that period. I just figured the sql query i wrote is wrong. It only prints the 1st value of the name column in the database. Help me to figure out how to sort according what i have mentioned above and print all the results that returned.
You might want to set the date in the where condition in your query.
select name,type,sum(amount),date_payed from expenses where date_payed = ? order by 4 DESC
Consider obtaining Date from String.
String reportDate = ((JTextField)report_date.getDateEditor().getUiComponent()).getText(); // "2017-01-01"
DateFormat format = new SimpleDateFormat("YYYY-MM-DD", Locale.ENGLISH);
Date date = format.parse(reportDate);
Then set your param with
pst.setDate(1,reportDate);

How to get TIME out of DATETIME MySQL using java.sql.Date

I have a DATA/TIME field in my MySQL database and I'm trying to convert it to date and time in Java. The date works fine, but in time is set to null. I have tried util.Date as well but I get the same result. How can I convert a DATE/TIME to java.sql.Date without losing the time?
This is my code
try{
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT orders.id, orders.date FROM user, orders " +
"WHERE user.username='" + user.getUsername() + "' AND user.id = orders.user");
while(resultSet.next()){
Order order = new Order();
order.setId(resultSet.getInt(1));
order.setUser(user);
order.setDate(resultSet.getDate(2));
System.out.print(order.getDate());
System.out.print( " -> " + order);
orders.add(order);
}catch(SQLException ex){
System.out.println(ex);
}
try this
java.sql.Date date = new Date(resultSet.getTimestamp(2).getTime());
You are not asking this, but you could save the date as a long in mysql and just treat it as a number.
To get the date back just do a new java.util.Date(mysqllong).

search database by date

I want to search column called name in my work table by searching date. Other columns are id(primary key) and mydate. I can't find what is wrong with my code. I'm using jdbc class for db connection.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jDateChooser1.getDate());
String time1 = dateSpinner1.getValue().toString().split(" ")[3];
date1 = date1 + " " + time1;
try {
ResultSet rs =db.getData("SELECT * FROM work WHERE mydate = '"+date1+"'");
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
date is the name of a function in MySQL. You'll need to wrap it in ` characters:
ResultSet rs =db.getData("SELECT * FROM work WHERE `date` = '"+date1+"'");
One possible error may be that in database hours minutes and seconds are not 0:0:0 and from datechooser you are getting these fields as 0 : 0
Could you pass the date1 as date in the statement (as parameter)?
"SELECT * FROM work WHERE date = ?" and pass parameter as date

Categories

Resources