More than one jTable with the same ResultSet in Java - java

Can you populate more than one jTable with the same resultSet?
public void tableDisplay() {
String tableQuery = "SELECT foodQuantity,foodName FROM food ORDER BY RAND() LIMIT 3";
ResultSet rs;
PreparedStatement statement;
try {
statement = con.prepareStatement(tableQuery);
rs = statement.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
The code compiles but the second table doesn't get any records from DB.
The point is that I need to select random items from mySql table and I want to display them in few jTables.

Without knowing too much about your code, I'd say that you need to call DbUtils.resultSetToTableModel(rs) once, and store the resulting table model in a local variable. Then, pass that local variable to the two setModel(...) methods

How I populate a JTable with resultSet
try{
playerTableModel = (DefaultTableModel)playerTable.getModel();
rs = controller.getPlayer();
while (playerTableModel.getRowCount() > 0);
int columns = playerTableModel.getColumnCount();
Object[] rows = new Object[columns];
while(rs.next()){
rows[0] = rs.getString(1);
rows[1] = rs.getString(2);
rows[2] = rs.getString(3);
rows[3] = rs.getString(4);
playerTableModel.addRow(rows);
}catch(Exception e){
e.printStackTrace();
}
Can't you just call same method for the second table too?

Related

Getting Multiple Data using Text field + Jbutton from SQL Server to Jtable

Good day, just wanna ask. I have a Java GUI where I want to add multiple data from SQL server to my Jtable. The flow here is that I would want to use the text field as search field where I will add the info for searching and use the Jbutton to perform the search action then it will give/show me the data to my Jtable. Actually the code is running however some of the data like the 1st data added to my SQL serve and from data id 7 and and up are not showing. How would I fix this and show multiple data with same order ID form SQL server?
Thank you!!
try {
String query = "select * from `sales_product` where order_id = ?";
pst = con.prepareStatement(query);
pst.setString(1, txsearch.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()) {
while(rs.next()) {
String prodname = rs.getString("prodname");
String price = String.valueOf(rs.getInt("price"));
String qty = String.valueOf(rs.getInt("qty"));
String total = String.valueOf(rs.getInt("total"));
model = (DefaultTableModel) datatable.getModel();
model.addRow(new Object[]{
prodname,
price,
qty,
total
});
int sum = 0;
for (int a = 0; a < datatable.getRowCount(); a++) {
sum = sum + Integer.parseInt(datatable.getValueAt(a, 3).toString());
}
Ltotal.setText(Integer.toString(sum));
}
}
else {
JOptionPane.showMessageDialog(this, "No order found!");
txsearch.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(milktea.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(rs.next()) {
while(rs.next()) {
No need for the if (rs.next()) statement. That is causing you to skip the first row of data in the ResultSet.
All you need is the while (rs.next()) statement to create the loop to read all rows in the ResultSet.

How to make the table size same as the row size in java?

I have retrieved data from SQL Database into a JTable. I want to make the table size to be automatically the size of the rows. It would be plus if I can also make the data in the rows centered.
I am fairly new to GUI Java Programming. Can someone please let me understand how it can be done?
private void DisplayOrder() {
String qry = "SELECT * FROM SALESORDER"; //Creating Query
try {
conn = DriverManager.getConnection(connectionUrl, username, Pass);
Statement st = conn.prepareStatement(qry);
ResultSet rs = st.executeQuery(qry);
while (rs.next()){
String Des = rs.getString("ProductDescription");
String qty = String.valueOf(rs.getInt("Quantity"));
String price = String.valueOf(rs.getInt("TotalPrice"));
String tbdata[] = {Des, qty, price};
DefaultTableModel model = (DefaultTableModel) Ordertable.getModel();
model.addRow(new Object[]{Des, qty, price});
}
} catch (SQLException e){
} finally{
Ordertable.getTableHeader().setFont(new Font("Segoe UI",Font.BOLD,15));
Ordertable.getTableHeader().setOpaque(false);
Ordertable.getTableHeader().setBackground(new Color(32,136,203));
Ordertable.getTableHeader().setForeground(new Color(255,255,255));
Ordertable.setRowHeight(25);
}
}

How to use Resultset?

I am using a mysql table, and now I need to compare a columns all values with a given String.
I want to check if all values of the result set matches with encryptedString.
Need to understand what result set does and how it works.
Here I have a method, Some variables, and 2 mysql queries.
final String secretKey = "!!!!";
String name = jText.getText();
String pass = jTextPass.getText();
String originalString = pass;
String encryptedString = AES.encrypt(originalString, secretKey) ;
String decryptedString = AES.decrypt(encryptedString, secretKey) ;
PreparedStatement PS;
ResultSet result;
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` =?";
PreparedStatement ps;
String query;
query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`=?";
try {
PS = MyConnection.getConnection().prepareStatement(query1);
PS.setString(1, name);
PS.setString(2, encryptedString);
rs = PS.executeQuery();
//while(result.next() ){
//I am not understanding what to do here.
ps = MyConnection.getConnection().prepareStatement(query);
ps.setString(1, encryptedString);
ps.setString(2, name);
ps.executeUpdate();
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
this.dispose();
//}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
}
First tip: using try-with-resources closes statement and result set even on exception or return. This also reduces the number of variable names for them because of the smaller scopes. This return from the innermost block I utilized. For unique names one can use if-next instead of while-next. A fail-fast by not just logging the exception is indeed also better; you can exchange the checked exception with a runtime exception as below, so it easier on coding.
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` = ?";
String query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`= ?";
try (PreparedStatement selectPS = MyConnection.getConnection().prepareStatement(query1)) {}
selectPS.setString(1, name);
//selectPS.setString(2, encryptedString);
try (ResultSet rs = selectPS.executeQuery()) {}
if (result.next()){ // Assuming `name` is unique.
String pass = rs.getString(1);
try (PreparedStatement ps = MyConnection.getConnection().prepareStatement(query)) {
ps.setString(1, encryptedString);
ps.setString(2, name);
int updateCount = ps.executeUpdate();
if (updateCount == 1) {
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
return success;
}
}
}
}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalStateException(e);
} finally {
dispose();
}
the ResultSet object contains all the information about the query that you perform, it will contain all columns. In your code the result variable will return anything since there is no part in your code where is executed, to do this you have to...
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
while(result.next()){
String column1 = result.getString("columnName");
}
The result.next() method is a boolean method that says if the ResultSet object still have values of the table inside and it will continue until it reaches the last row that your SELECT statement retrives. Now if you want to match the value of some column with other variables you can do it inside the while(result.next()).
result.getString("columnName") will extract the value from columnName as a String.
If you want to save things in an ArrayList to save the data and then use this list as you want the code can be like...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
List<Object> data = new ArrayList();
while(result.next()){
data.add(result.getString("columnName"));
}
return data;
Obviously you have to change the Object with the type of things that you want to store in the List.
Or if you want to store the data in an array. As I said in my comment this won't be dinamic, but...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
String[] data = new String[NUMBER_OF_COLUMNS_IN_RESULTSET];
while(result.next()){
data[0] = result.getString("columnName1");
data[1] = result.getString("columnName2");
data[2] = result.getString("columnName3");
//And so on...
}
return data;
The other way is that if you are returning an entity you can set the values of the ResultSet directly in the POJO:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
Entity entity = new Entity();
while(result.next()){
entity.setColumnName1(result.getString("columnName1"));
entity.setColumnName2(result.getString("columnName2"));
entity.setColumnName3(result.getString("columnName3"));
//And so on...
}
return entity;
There are so many ways to store the data, just ask yourself how do you want to receive the data in the other parts of you code.
Regards.

java - cant insert multiple data to database

i have some code that will save into two database but the other one can't saving into database. the one that can't to save is inserting multiple row data from jtable with 3 values but i have 5 columns in database because i need to fill it temporary with the other values are null. this is the code :
private void btnSimpanActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String sql="INSERT INTO pinjam VALUES('"+noPeminjaman.getText()+
"','"+noMember.getText()+"','"+tglPinjam.getText()+"',1)";
java.sql.Connection conn = (Connection)Config.configDB();
java.sql.PreparedStatement pst = conn.prepareStatement(sql);
pst.execute();
//Simpan ke pinjam_detil
int rows = tabelPinjam.getRowCount();
for(int row = 0; row<rows; row++){
String idBuku = (String)tabelPinjam.getValueAt(row, 0);
String tglTempo = (String)tabelPinjam.getValueAt(row, 2);
try{
String query = "INSERT INTO pinjam_detil (idpinjam,idbuku,tgl_tempo) "
+ "VALUES(?,?,?)";
java.sql.PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, noPeminjaman.getText());
stmt.setString(2, idBuku);
stmt.setString(3, tglTempo);
stmt.addBatch();
stmt.executeBatch();
}catch(Exception ex){}
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}catch(Exception e){}
resetForm();
}
Don't catch an exception and do nothing. Preferably, add a throws clause to the method, like so:
private void doThingie() throws SQLException {}
and if that's not an option, this should be in your catch block:
new RuntimeException(e);
because right now some error is happening and you can't tell because you're silently ignoring it.
Also, it's just stmt.execute();, not addBatch+executeBatch

Problems in removing records from database of jList

Hello I have the problem.. can anyone give me snippet? i have the table of MySql that display JList item so I can add the item easily but can't remove it from database? while pressing remove item?
I searched a lot no one has ever need of doing.. i wonder how its possible?
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","ubuntu123");
PreparedStatement stmt = null;
ResultSet rs = null;
String [] data;
data = new String[100];
int i=0;
DefaultListModel listmodel = (DefaultListModel) jList2.getModel();
int selectedIndex = jList2.getSelectedIndex();
if (selectedIndex != -1) {
listmodel.remove(selectedIndex);
String query = "delete from supplierinfo where companyname = ?";
stmt = (PreparedStatement) con.prepareStatement(query);
stmt.setInt(1, i);
stmt.execute();
con.close();
// i= i+1;
}
} catch(Exception e) {
System.out.println("3rd catch " +e);
}
}
You can save element in a variable when you remove it from ListModel.
After that you can get all important info about this item and use it in your query.
Use something like this:
YourObjectType obj = (YourObjectType) listmodel.remove(selectedIndex);
String query = "delete from supplierinfo where companyname = ?";
stmt = (PreparedStatement) con.prepareStatement(query);
stmt.setInt(1, obj.getCompanyName());
stmt.execute();
Use the ListModel#getElementAt(int) method with the currently selected index.
If you are certain your model only contains String instances, you can directly cast it to a String, then replace i with this string in stmt.setInt(1, i);

Categories

Resources