How To Get Data Between Two Dates In MySQL Using Java NetBeans
In this Java Tutorial we will see How To Search Data Between 2 Date From MySQL Database Using JDateChooser And Display The Result Into A JTable On JButton Click In Java NetBeans .
Project Source Code:
// to add some style to the jtable we will add this code below the "initComponents();"
jTable1.setRowHeight(40);
jTable1.setShowGrid(true);
jTable1.setGridColor(Color.yellow);
jTable1.setSelectionBackground(Color.black);
// this function will display all the data from mysql database
showData("", "");
// create a function to connect with mysql database
public static Connection getConnection()
{
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return con;
}
// create a function to show data between to date
// this function take to parameters d1( first date ), d2( second date )
public void showData(String d1, String d2)
{
Connection con = getConnection();
PreparedStatement st;
ResultSet rs;
try{
// if no date selected display all data
if(d1.equals("") || d2.equals(""))
{
st = con.prepareStatement("SELECT * FROM student");
}else{
st = con.prepareStatement("SELECT * FROM student WHERE BirthDate BETWEEN ? AND ?");
st.setString(1, d1);
st.setString(2, d2);
}
rs = st.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
Object[] row;
while(rs.next()){
row = new Object[4];
row[0] = rs.getInt(1);
row[1] = rs.getString(2);
row[2] = rs.getString(3);
row[3] = rs.getString(4);
model.addRow(row);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
// Button To Display The Data
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
jTable1.setModel(new DefaultTableModel(null, new Object[]{"Id","Full Name","Address","BirthDate"}));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String date1 = df.Format(jDateChooser1.getDate());
String date2 = df.Format(jDateChooser2.getDate());
showData(date1, date2);
}catch(Exception e){
}
}
OutPut:
Download Projects Source Code