Getting all data between 2 days in MySql Java - java

I want to select all data from database table between given 2 specific dates and add that data to a jtable.
Below is my code to retrieve data from the database; But all the data is not shown by this code .. What is the error I done here?
private void updateTable(){
String fday = ((JTextField)day_chooser.getDateEditor().getUiComponent()).getText();
String tday = ((JTextField)day_chooser.getDateEditor().getUiComponent()).getText();
try {
String sql = "SELECT * FROM saleinfo WHERE SaleDate BETWEEN '"+fday+"' AND '"+tday+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
tbl.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : "+ex);
}
}

Leverage the JDBC drive and it's ability to map between data types from Java to the database, leverage the power of the PreparedStatement
I'm using prepared statements pst is the prepare statement
BUT, you're not using it properly, see Using Prepared Statements for more details.
Start by getting the Date value from the date picker (I'm guessing here, but I assume they have some kind of getDate method) and then bind the values to the wildcard columns of the query, for example...
Date fday = day_chooser.getDate();
Date tday = day_chooser.getDate();
try {
String sql = "SELECT * FROM saleinfo WHERE SaleDate BETWEEN ? AND ?";
try (PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setDate(1, new java.sql.Date(fday.getTime()));
pst.setDate(2, new java.sql.Date(tday.getTime()));
try (ResultSet rs = pst.executeQuery()) {
tbl.setModel(DbUtils.resultSetToTableModel(rs));
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : " + ex);
ex.printStackTrace();
}
Don't assume anything about the format, this will just cause you no end of grieve if you ever have to change databases

Related

how to get data from result set by selecting multiple table record using JDBC?

I am trying to get data using result set from multiple tables which throw exception.
java.sql.SQLException: Invalid column name.
public void test(String code) {
String sql = "select * from table1 ,table2 where table1.code = table2.code and table.code='" + code + "'";
try (PreparedStatement pst = conn.prepareStatement(sql); ResultSet rs = pst.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("table1.code"));
}
} catch (SQLException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
using this statement it's work find but it's take more time to every individual column and it's bad practice.
select table1.code as code,table1.name as name ....,table2.code as
tbl2Code,... where table1.code=table2.code;

Query executed twice (by error) in Java with unwanted values

I'm using JFreeChart to create a chart in Java and MySQL.
When I try to insert my values in another table the query seems to be executed twice since I end up with the same timestamps multiple times...
Here's a part of my code :
private JDBCXYDataset createDataset() {
try {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:bd?serverTimezone=UTC","MySQL", "MySQL");
conn.setAutoCommit(false);
SQLException savedException = null;
Statement st = conn.createStatement();
st.execute("DROP TABLE IF EXISTS test ");
st.execute("create table test(Table timestamp, Table float,Table float)");
String Date_Debut = "2020-06-25 00:00:00";
String Date_Fin = "2020-06-26 00:00:00";
String sql1 = "INSERT INTO test (Table ,Table ,Table ) "
+ "SELECT Table ,Table ,Table "
+ "FROM Table "
+ "WHERE Table BETWEEN ? AND ? ";
try ( PreparedStatement ps = conn.prepareStatement(sql1)){
ps.setString(1,Date_Debut);
ps.setString(2, Date_Fin);
ps.executeUpdate();
ps.close();
JDBCXYDataset jds = new JDBCXYDataset(conn);
st.close();
jds.executeQuery("SELECT Table ,Table ,Table FROM test");
conn.commit();
return jds;
} catch (SQLException ex) {
savedException = ex;
conn.rollback();
} finally {
conn.setAutoCommit(true);
if(savedException != null) {
throw savedException;
}
}
} catch (SQLException ex1) {
}
return null;
}
EDIT : Actually it seems like the errors where comming directly from the database, the moderators can delete this post if they want. However I keep Trashgod's response validated as it was more than helpful.
For everyone that might come here with a similar issue, inspect in detail your database first to see if it isn't comming from there instead of your code.
Chasing down anomalies in data is arduous, but JFreeChart can at least make the result easier to visualize. Some heuristics for testing:
To verify that the the presumed duplicates in your tabular listing are indeed duplicates, format the timestamps to include milliseconds, e.g. add an S to a SimpleDateFormat or A to a DateTimeFormatter.
For study, temporarily pass the query directly to JDBCXYDataset, and add an ORDER BY clause (untested):
jds.executeQuery(
"SELECT Date_Heure, PV, SV FROM cmd3 "
+ "WHERE Date_Heure BETWEEN "
+ "2020-06-25 00:00:00 AND 2020-06-26 00:00:00 "
+ "ORDER BY Date_Heure");
Enable tooltips in your ChartFactory, as you did here, to see data values in situ. This may suggest additional conditions for your WHERE clause, e.g. PV BETWEEN 5.1 AND 5.9.
Use the interactive JFreeChart pan/zoom controls, discussed here to examine the data; add suitable buttons, shown here, if it will make it easier for colleagues to see your findings.
By design, JDBCXYDataset executes a query defined by a String. If your design needs to display data from a query defined by a PreparedStatement, you can use the existing implementation as a guide.
public class PreparedDataset extends AbstractXYDataset
implements XYDataset, TableXYDataset, RangeInfo {
private final PreparedStatement ps;
public PreparedDataset(PreparedStatement ps) {
this.ps = ps;
}
…
}

SQL Lite Query (between in dates) doesn't work

in my small test program I have some SQL Queries. The first SELECT * FROM kilometer; works properly and returns all the columns in the table. So in Java embedded, ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer;"); returns an ResultSet which is not empty.
Now I wanted to get only the rows within a specific date. But my embedded query ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer WHERE datum BETWEEN '2016-01-01' AND '2016-12-31';"); returns an empty ResultSet. But I've tested it online and it worked properly. Where is my mistake? I've consulted already some pages like this, but I can't find the mistake.
I am using SQLite 3.15.1 and Java SE 8.
Full java code:
public ArrayList<Strecke> getErgebnisse(final String startzeitpunkt, final String zielzeitpunkt) {
ArrayList<Strecke> strecken = new ArrayList<>();
try {
try {
if (connection != null) {
}
connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
if (!connection.isClosed())
} catch (SQLException e) {
throw new RuntimeException(e);
}
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer WHERE datum BETWEEN '2016-01-01' AND '2016-12-31';");
while (rs.next()) {
strecken.add(new Strecke(Instant.ofEpochMilli(rs.getDate("datum").getTime()).atZone(ZoneId.systemDefault()).toLocalDate(), rs.getString("startort"), rs.getString("zielort"), rs.getDouble("kilometer")));
}
rs.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return strecken;
}
First of all I would recommend that you use prepared statements while executing your queries instead of passing the query directly as a string......secondly I believe the problem here is that you are passing the date as a string in quotes and not a date.....I think that is the issue here. You would need to use sqllites datetime functions for this....

Inserting data from a database into a jTable in netbeans

I'm trying to put data from my database into a jTable and the program isn't throwing an error, but it does nothing. This is the method I'm using. Thanks for the help.
public void displayTable()
{
try
{
Connection con = DriverManager.getConnection("jdbc:ucanaccess://TransactionTrackerDB.accdb");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT transactionID, startDate, description, totalSum,"
+ " instalments, balanceDue FROM RecurringExpense ORDER BY transactionID DESC";
ResultSet rs = stmt.executeQuery(SQL);
display.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (SQLException ex)
{
Logger.getLogger(MonthlyExpensesClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
To put data from database into a jTable I always use user specified method such as below;
Note - I'm not including getting connection with the database codes. list_table is the table that you want to show database content.
private void updateTable(){
try {
//getting data from the mysql database
String sql = "SELECT transactionID, startDate, description, totalSum,"
+ " instalments, balanceDue FROM RecurringExpense ORDER BY transactionID DESC";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
list_table.setModel(DbUtils.resultSetToTableModel(rs));
// re sizing the column width
list_table.getColumnModel().getColumn(0).setPreferredWidth(15);
//as this change getColumn(column number) and size the columns
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error : "+ex);
}
}
Then call the defined updateTable(); as you want to retrieve data from the database.

Updating existing Row on database jdbc

No error is showing when i click the button but the table on the database doesn't update.
String heh = jLabel17.getText();
try {
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch (SQLException err) {
System.out.println(err.getMessage() );
}
You have messed up the query totally,
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
should be,
stmt.executeUpdate("UPDATE books SET availability='Unavailable' where Book_title='"+heh+"' ");
It is advisable to print query before you execute , as that avoids common mistakes. Also try to use Prepared Statements as yours is vulnerable to sql injection
Read this Prepared Statements and JDBC Drivers
AFTER HOURS OF RESEARCH, I FOUND THE SOLUTION, I REPLACED THIS
String heh = jLabel17.getText();
try{
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch(SQLException err){
System.out.println(err);
}
WITH THIS CODE
String heh = jLabel17.getText();
try{
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Dafuq7","Dafuq7","Dafuq7");
// Creating Statement for query execution
stmt = con.createStatement();
// creating Query String
String query = "UPDATE books SET availability='NOT AVAILABLE' WHERE book_title='"+heh+"'";
// Updating Table
int rows = stmt.executeUpdate(query);
System.out.println(rows + " Rows Updated Successfully....");
} catch (Exception e) {
System.out.println(e.toString());
}

Categories