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
Related
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);
I'm having problem with showing database values in my Jtable. I don't know how to use JDataChooser as a searching tool in JTable. I want the process like this, if JDateChooser1 is select to 08-17-2017 and JDateChooser2 is select 09-17-2017
the JTable will only show the values that having that date between 08-17-2017 - 09-17-2017. The format of the Date is (MM-dd-yyyy).
I have this method and as a testing I put the method to a button. I also want to know where I can put this method to be able not using a button. Auto search when I'm done selecting the dates.
sales is my table name in mysql and Date is the column name.
private void Dated() {
try {
String value1, value2;
value1 = jDateChooser1.getDate().toString();
value2 = jDateChooser2.getDate().toString();
String sql = "select * from sales where Date = '" + value1 + "' and '" + value2 + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
You are missing some information in your query :
show the values that having that date between 08-17-2017 - 09-17-2017 you have to use between keyword in the query should be select * from sales where Date between date1 and date1 and not =
because you are using prepapred statement don't use concatination of the query and values.
beside Date is reserved keyword in MySQL instead you have to put it between two ``
Your code should look like :
Date value1 = jDateChooser1.getDate();
Date value2 = jDateChooser2.getDate();
String sql = "select * from sales where `Date` between ? and ?";
pst = conn.prepareStatement(sql);
pst.setDate(1, value1);
pst.setDate(2, value2);
rs = pst.executeQuery();
I am having a tough time to figure out how I can insert DATE type record in to derby database. I have created a table with column type TIME_EXECUTED DATE NOT NULL. Below is the query
public void addMetric(String provider, Date date) {
try {
Statement stmt = conn.createStatement();
String inserTableSql = "INSERT INTO tableName"
+ "(PROVIDER,TIME_EXECUTED) VALUES"
+ "(?,?)";
PreparedStatement p=conn.prepareStatement(inserTableSql);
p.setString(1, provider);
p.setDate(9, date);
ResultSet rs=p.executeQuery();
stmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
This is how I am passing date in the method
private static java.sql.Date getCurrentDate() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}
This is the error I am getting ERROR 22007: The syntax of the string representation of a date/time value is incorrect.
Any help will be very helpful. Thanks
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).
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.