Show results on Jtable between dates when selected Jdatechooser (Mysql) - java

This is the query for the (between dates). But when I select the dates and click OK all records on JTable disappears. Help me to build the query and statement for the get record between dates on JTable.
Jtable with records
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here
// java.util.Date val1 = jDateChooser1.getDate();
// java.util.Date val2 = jDateChooser2.getDate();
java.sql.Date val1 = new java.sql.Date(jDateChooser1.getDate().getTime());
java.sql.Date val2 = new java.sql.Date(jDateChooser2.getDate().getTime());
try {
String sql = "select * from Umar where Date between ? and ? ";
pst = conn.prepareStatement(sql);
pst.setDate(1, val1);
pst.setDate(2, val2);
rs = pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null,e);
}
}

Once again we know nothing about your database. It is up to you to know how the data is displayed in the database.
Here is a simple query to get you started.
String sql = "Select * from Umar";
PreparedStatement ps = connection.prepareStatement();
ResultSet rs = ps.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
System.out.println( md.getColumnLabel(i) );
}
// Get row data
while (rs.next())
{
for (int i = 1; i <= columns; i++)
{
Object data = rs.getObject(I);
System.out.println(data + " : " + data.getClass());
}
}
rs.close();
stmt.close();
This has absolutely nothing to do with your JTable. It is just a query of the database. So get this query working. Determine how the date is stored in your database. Is it a String or a Date?
Then next you change the query:
String sql = "Select * from Umar where Date between ? and ? ";
...
ps.setDate/String(1, ...);
ps.setDate/String(2, ...);
Then you test this with a hard coded data to make sure you get data. Then once this step is working you fix your program that loads the data into the JTable.

Related

SQLite row disappears after executing select query

I am using SQLite database with java servlets for my cinema application.
I have DAO which communicates with db. After making select query to database, random row gets deleted.
Here is the method that gives me list of projections based on movie, but it somehow deletes row in the table everytime it gets called. (It always deletes row on top and after that random rows).
public static List<Projection> getAllByMovie(Integer movie_id) {
List<Projection> projections = new ArrayList<>();
Connection con = ConnectionManager.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "SELECT * FROM projections WHERE movie = ? AND dateandtime >= '2020-02-11'";
ps = con.prepareStatement(query);
ps.setInt(1, movie_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
rs = ps.executeQuery();
while (rs.next()) {
int index = 1;
int id = rs.getInt(index++);
int title = rs.getInt(index++);
int projection_type = rs.getInt(index++);
int theater_rs = rs.getInt(index++);
String date_and_time = rs.getString(index++);
double price = rs.getDouble(index++);
int admin_creator = rs.getInt(index++);
Theater theater = TheaterDAO.get(theater_rs);
Movie movie = MovieDAO.get(title);
ProjectionType projectionType = ProjectionTypeDAO.get(projection_type);
Projection projection = new Projection();
projection.setId(id);
projection.setMovie(movie.getTitle());
projection.setProjectionType(projectionType.getName());
projection.setTheater(theater.getName());
Date date = sdf.parse(date_and_time);
projection.setDateOutput(date_and_time);
projection.setDateAndTime(date);
projection.setTicketPrice(price);
projection.setAdminCreator(admin_creator);
projections.add(projection);
}
} catch(Exception ex) {
ex.printStackTrace();
} finally {
try {ps.close();} catch (Exception ex1) {ex1.printStackTrace();}
try {rs.close();} catch (Exception ex1) {ex1.printStackTrace();}
}
return projections;
}
I always get desired result with this query, but it randomly removes row.
I have many other methods and queries for database, but none invokes this kind of behaviour.
EDIT: I came to conclusion, initially there are 25 projections (rows) in table, it deletes rows until there's 15 left! (first 10 rows get deleted, first row then other 9 in random order)
What the hell is going on?

Unable to create/modify sqlite tables from Java application

I have a basic java application and a sqlite DB.
I can create table manually through sqLite browser. And I am able to access these tables from my JAVA application.
E.g. Reading from existing table: (I have omitted the try catch blocks in the sample below just to reduce the length of question)
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "select * from test1 where uname = ? and name = user1";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, "test");
resultSet = preparedStatement.executeQuery();
if(resultSet.next())
return true;
else
return false;
I am able to perform this query successfully.
However, if I create / modify a table, changes does not show up in SQlite DB (I am viewing db in sqLite browser). If I copy paste the same query in SQlite browser, the query runs successfully and a row is added.
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "INSERT INTO COMPANY (ID,NAME,AGE) VALUES (3, 'tOM', 32);";
preparedStatement = connection.prepareStatement(query);
preparedStatement.executeUpdate();
Am I missing something?
EDIT: Both the above tables exist in my sqlite db. Both were created through sqlite browser
EDIT2: I was getting true from my example 1 above, that's why I felt that I am able to read from db. I update my code to print the data read and nothing gets printed which means I am not able to read the data as well:
resultSet = preparedStatement.executeQuery("SELECT * FROM test1");
and
private static void outputResultSet(ResultSet rs) throws Exception {
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
System.out.print(columnName + " ");
}
System.out.println();
System.out.println("----------------------");
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
}
The connection string is:
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\akshay\\sqlite_test.sqlite");
conn.setAutoCommit(true);
return conn;

Deleting selected row in MySQL database through JTable

tb_records = jtable name
records = table name inside my database
Date = my first column
hey = substitute for my real password
mydatabase = name of my database
My problem is that, when I highlight a row in my JTable and delete it, it deletes all the rows. I want to delete the selected row only. Here's my code:
int row = tb_records.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tb_records.getModel();
String selected = model.getValueAt(row, 0).toString();
if (row >= 0) {
model.removeRow(row);
try {
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "hey");
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
ps.executeUpdate();
}
catch (Exception w) {
JOptionPane.showMessageDialog(this, "Connection Error!");
}
}
What could be the problem here? How can I delete a selected row in my database and not all the rows?
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
int row = jTable.getSelectedRow();
String eve = jTable.getModel().getValueAt(row, 0).
String delRow = "delete from user where id="+eve;
try {
ps = myCon.getConnection().prepareStatement(delRow);
ps.execute();
JOptionPane.showMessageDialog(null, "Congratulation !!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
1) Don't display your own message. Display the error message from the Exception as it will give a better explanation what the problem is.
2) Use a proper PreparedStatement for the SQL. You are less likely to make syntax errors. Something like:
String sql = "delete from records where Date= ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, selected );
stmt.executeUpdate();
I don't know much about SQL but maybe you need to pass a Date object not a String object since your where clause is using a Date?
The OP wrote:
SOLUTION: Pick a column with unique values. My Date column has the same values that's why it's deleting all my rows even though I set my row as getSelectedRow. Time_in = my 4th column with unique values.
change
String selected = model.getValueAt(row, 0).toString();
to
String selected = model.getValueAt(row, 3).toString();
and
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
to
PreparedStatement ps = conn.prepareStatement("delete from records where Time_in='"+selected+"' ");

Cant get records between two dates

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 "

ResultSet returns only last row into JTable

I have done enough searches to solve my problem which i have done partly but there's this one bug that keeps disturbing me.I am trying to fetch data from a database based on a condition.I have a table 'user_branch' with a foreign key column branchID which is supposed to fetch the coresponding branchNames in another table 'branches' and I am supposed to display the results into a JTable.When i do System.out.println i get all my results but it returns only the last row when i display in a JTable(branchJTable).This is the code i am using
int row = user2BAssignedJTable.getSelectedRow();
assignUserID.setText(user2BAssignedJTable.getModel().getValueAt(row, 0).toString());
user2BAssignedField.setText(user2BAssignedJTable.getModel().getValueAt(row, 1).toString());
try {
String userBrQry = "SELECT branchID FROM user_branch WHERE userID IN(?) ";
String brQ = "SELECT branchName FROM branches WHERE branchID IN(%s) ";
pstmt = con.prepareStatement(userBrQry);
pstmt.setString(1, assignUserID.getText());
results = pstmt.executeQuery();
results.last();
int nRows = results.getRow();
results.beforeFirst();
while (results.next()) {
String branchIDS = results.getString("branchID");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < nRows; i++) {
builder.append("?");
if (i + 1 < nRows) {
builder.append(",");
}
}
brQ = String.format(brQ, builder.toString());
PreparedStatement ps = con.prepareStatement(brQ);
for (int i = 0; i < nRows; i++) {
ps.setString(i + 1, branchIDS);
}
ResultSet rs = ps.executeQuery();
//branchJTable.setModel(DbUtils.resultSetToTableModel(rs));
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
while (rs.next()) {
String branchname = rs.getString("branchName");
model.addRow(new Object[]{branchname});
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Forget about the first 3 rows as it is a another JTable event i use to get the userID to use as a condition for getting a particular user's branches assigned to him.
The branches assigned to a user is dynamic hence using StringBuilder.
I am supposed to display the results into another JTable called branchJTable which only displays the last row.Any HELP would be appreciated!
From your question, I think you should declare the JTable
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
before your first loop -
i.e. before while (results.next()) { in your code.
Otherwise in loop, for each loop execution,
the JTable Model is initialising and you are getting the last inserted row in Jtable.

Categories