Java- check if dataset from table already exists - java

I select the datasets with a button from my database table, but every time I click on the button it loads the same datasets I already have:
public void actionPerformed(ActionEvent e) {
java.sql.Connection con;
try {
con = DriverManager.getConnection ("jdbc:mysql://localhost:3307/lessons","root","");
String query =" SELECT * FROM lessons";
PreparedStatement statement = con.prepareStatement(query);
ResultSet rs = statement.executeQuery(query);
while(rs.next())
{
int lesson = rs.getInt("lessons");
String name= rs.getString("names");
String number= rs.getString("numbers");
model.addRow(new Object[]{lessons, names, numbers});
table.setVisible(true);
}
I just want to print the datasets which are unique.
Thank you all in advance.

You have to remove all available rows before loading data to table
DefaultTableModel model = (DefaultTableModel)your_table.getModel();
...
model.setRowCount(0); // add this line
while(rs.next()) {
int lesson = rs.getInt("lessons");
String name= rs.getString("names");
String number= rs.getString("numbers");
....
model.addRow(new Object[]{lessons, names, numbers});
}

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);
}
}

Sqlite Column Determination Error

I'm trying to get selection from J combo Box and use that to find table from the data base. But instead an error comes up:
My codes it:
JButton btnGo = new JButton("Go!");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Connection conni = null;
ResultSet rs=null;
PreparedStatement pst=null;
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String x = comboBox.getSelectedItem().toString();
String sql="select * from " + x;
pst=conni.prepareStatement(sql);
rs=pst.executeQuery();
while(rs.next()){
String name = rs.getString("Namet");
nameofguy.setText(rs.getString(name));
}
}catch(Exception i){
JOptionPane.showMessageDialog(null, i);
}
I'm searching for table.. but it says cannot find column.
Here's your problem
while(rs.next()){
String name = rs.getString("Namet");
//rs.getString returns Ayaan. So value of name is "Ayaan"
nameofguy.setText(rs.getString(name));
// Youre trying to get the value corresponding to the column Ayaan here
//This is why the exception is thrown as there is no column called Ayaan
}
Instead do
while(rs.next()){
String name = rs.getString("Namet");
nameofguy.setText(name);
}

More than one jTable with the same ResultSet in 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?

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