how to fetch multiple rows from mysql to java table in swings - java

i have a swing application which consists of a text box and a button.On entering the emp_id and clicking the button it connects to mysql and fetch all the rows corresponding to the emp_id entered in a table. my code is fetching only 1 row of the mysql data, even though there is 3 rows corresponding to the emp_id
my code is:
try {
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, userName,password);
String sql = "select * from devices where emp_id = " + textvalue;
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i = 0;
if (rs.next()) {
asset_id = rs.getString("asset_id");
name = rs.getString("name");
project = rs.getString("project");
emp_id = rs.getString("emp_id");
emp_name = rs.getString("emp_name");
model.addRow(new Object[] { asset_id, name, project, emp_id,emp_name });
// i++;
}
if (i < 1) {
JOptionPane.showMessageDialog(null, "No Record Found", "Error",JOptionPane.ERROR_MESSAGE);
}
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400, 300);

you are fetching only first row.. fetch it in a loop
while(rs.next())
{
asset_id = rs.getString("asset_id");
name = rs.getString("name");
project = rs.getString("project");
emp_id = rs.getString("emp_id");
emp_name=rs.getString("emp_name");
model.addRow(new Object[]{asset_id, name, project, emp_id,emp_name});
//i++;
}

You get only one row from ResultSet :
if (rs.next()) {
asset_id = rs.getString("asset_id");
name = rs.getString("name");
project = rs.getString("project");
emp_id = rs.getString("emp_id");
emp_name = rs.getString("emp_name");
model.addRow(new Object[] { asset_id, name, project, emp_id,
emp_name });
// i++;
}
replace if with while, for getting all rows in loop.
For centring frame use frame.setLocationRelativeTo(null);.
According to docs
If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method.
Also:
1) replace next code:
if (i == 1) {
System.out.println(i + " Record Found");
} else {
System.out.println(i + " Records Found");
}
with System.out.println(i + " Record Found"); because its code duplication.
2)Don't use setSize(...) use pack() method.
3)Call frame1.setVisible(true); in last line of construction or like next:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});

Related

Unable to query database correctly using JDBC

I am trying to update a database using input from user and saving it in jtable, then using jtable I am updating the database, but I am not able to get fetch and update 2nd row in database.
please suggest a solution, Thanks in advance.
try {
Class.forName("com.mysql.jdbc.Driver");
con = myconnection.getConnection();
String name;
for (int i = 0; i < jTable2.getRowCount(); i++) {
name = (String) jTable2.getModel().getValueAt(i, 0);
String abcd = "select * from medicine where Name=? ";
stmt = conn.prepareStatement(abcd);
stmt.setString(1, name);
rs = stmt.executeQuery();
if (rs.next()) {
name = (String) jTable2.getModel().getValueAt(i, 0);
String stock = rs.getString("qty");
int nowstock = Integer.parseInt(stock);
int qty1 = Integer.parseInt(jTable2.getValueAt(i, 2).toString());
int newstock = nowstock - qty1;//Integer.parseInt(jTable2.getValueAt(i, 2).toString());
String sqlupdate = "UPDATE medicine SET qty='" + newstock + "'WHERE Name='" + name + "' "; //
stmt = conn.prepareStatement(sqlupdate);
stmt.executeUpdate();
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Bill.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Bill.class.getName()).log(Level.SEVERE, null, ex);
}
The select serves no purpose, and you can just iterate all names and update directly:
for (int i=0; i < jTable2.getRowCount(); i++) {
String name = (String) jTable2.getModel().getValueAt(i, 0);
int qty1 = Integer.parseInt(jTable2.getValueAt(i, 2).toString());
String update = "UPDATE medicine SET qty = qty - ? WHERE Name = ?";
PreparedStatement ps = conn.prepareStatement(update);
ps.setInt(1, qty1);
ps.setString(2, name);
ps.executeUpdate();
}
If your JTable happens to have more than say 10 or so names, then a more efficient way to do this would be to use a single update with a WHERE IN clause containing all names which appear in the table, i.e.
UPDATE medicine SET qty = qty - ? WHERE Name IN (...);

How to make buttons with conditions from the mysql command in java?

I am making an application for booking a movie ticket, then I want to make a button for selecting seat numbers by checking several conditions on the database.
I use JButton with the following actions:
private void A1ActionPerformed (java.awt.event.ActionEvent evt) {
        try {
            Object day = cmbHari.getSelectedItem ();
            Object stud = cmbStud.getSelectedItem ();
            String sql = "SELECT * FROM message where id_kursi = '" + A1.getText () + "' AND id_film = '" + txtIDFilm.getText () + "' AND start = '" + txtJam.getText () + "' AND day = '"+ day +"' AND studio = '"+ stud +"' ";
            Stat statement = conn.createStatement ();
            ResultSet result = stat.executeQuery (sql);
            if (result.equals (true)) {
                JOptionPane.showMessageDialog (null, "Seat has been booked");
            } else {
                JOptionPane.showMessageDialog (null, "Seat booked");
                txtKur.setText ("A1");
            }
        } catch (SQLException ex) {
            Logger.getLogger (belitiket.class.getName ()). Log (Level.SEVERE, null, ex);
        }
    }
But always the seats can be ordered even though all conditions are fulfilled, the seats should not be ordered.
EDIT:
Thanks guys, solved.
private void A1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Object hari = cmbHari.getSelectedItem();
String h=hari.toString();
Object stud = cmbStud.getSelectedItem();
String s=stud.toString();
String insert = "select 1 from pesan where id_kursi=? and id_film=? and mulai=? and hari=? and studio=?;";
PreparedStatement ps = conn.prepareStatement(insert);
ps.setString(1, A1.getText());
ps.setString(2, txtIDFilm.getText());
ps.setString(3, txtJam.getText());
ps.setString(4, h);
ps.setString(5, s);
ResultSet rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Kursi Sudah Dipesan");
txtKur.setText("");
}else{
JOptionPane.showMessageDialog(null, "Kursi Dipesan");
txtKur.setText("A1");
}
} catch (SQLException ex) {
Logger.getLogger(belitiket.class.getName()).log(Level.SEVERE, null, ex);
}
}
The ResultSet is an iterative item and not a boolean to be compared to.
Also if you don't need a result use SELECT 1 ... that way if there is an item there will be a result and it can be done quickly on the server rather than marshalling unneeded information.

Resultset always empty when doing executeQuery

I am currently writing a simple Java app that reads information from an XLS file and then enters it in the database. Since that XLS does have duplicated records, I do a simple check if the entry in the XLS file already exists in the database. Here is my code:
public static void addResult(ArrayList<ArrayList<String>> listResults)
{
try
{
openDatabase();
stmt = c.createStatement();
for (int i = 0; i < listResults.size(); i++)
{
PreparedStatement stm = c.prepareStatement("SELECT player_name FROM results WHERE player_name=?;");
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
System.out.println(stm);
ResultSet rs = stm.executeQuery();
if (rs.getRow() <= 0)
{
String typeOfPlay = new String();
if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Simple"))
{
typeOfPlay = "single";
}
else if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Double"))
{
typeOfPlay = "double";
}
stm = c.prepareStatement("INSERT INTO results (player_name, school_id, " + typeOfPlay + ", tournament_id) "
+ "VALUES(?,?,?,?);");
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
stm.setString(2, listResults.get(i).get(ReadResultsFile.SCHOOL_ID));
stm.setInt(3, Integer.parseInt(listResults.get(i).get(ReadResultsFile.SCORE)));
stm.setString(4, "1");
stm.executeUpdate();
}
else
{
String typeOfPlay = new String();
if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Simple"))
{
typeOfPlay = "single";
}
else if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Double"))
{
typeOfPlay = "double";
}
stm = c.prepareStatement("UPDATE results SET " + typeOfPlay + "=? WHERE player_name=?;");
stm.setString(1, typeOfPlay);
stm.setString(2, listResults.get(i).get(ReadResultsFile.SCORE));
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
System.out.println(stm);
stm.executeUpdate();
}
}
closeDatabase();
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
The problem that arises is that the rs.getRow() function always returns -1. I tried running the SELECT query directly in the database tool and the query returns the player_name column if there is already a similar entry existing. It unfortunately do the same in Java.
I am unsure what to do at this point.
Thank you for any hint!
getRow will not work as per the javadocs
Retrieves the current row number. The first row is number 1, the second number 2, and so on.
and
A ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row
Usually use
while (rs.next ()) {....

NullPointerException in Java TableRowSorter

I made a jtable for the list of chemicals in the inventory where I can sort each columns using the following code (chemicalTable is the name of the jTable):
chemicalTable.setAutoCreateRowSorter(true);
TableRowSorter<TableModel> sorter1
= new TableRowSorter<TableModel>(chemicalTable.getModel());
chemicalTable.setRowSorter(sorter1);
Then I used a jTextfield to create a searchbox with a keyTyped Listener so that whenever the user types a certain character the table refreshes. And it usually works.
I used this code in the keyTypedListener for the searchbox:
DefaultTableModel dm = (DefaultTableModel) chemicalTable.getModel();
str = searchChemicalText.getText();
try {
String url = "jdbc:mysql://localhost/chemical inventory";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, "root", "");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error Occurred.", "Error", JOptionPane.ERROR_MESSAGE);
}
int ctr = 0;
while (ctr < chemicalTable.getRowCount()) {
chemicalTable.getModel().setValueAt(null, ctr, 0);
chemicalTable.getModel().setValueAt(null, ctr, 1);
chemicalTable.getModel().setValueAt(null, ctr, 2);
ctr++;
}
int count = 0;
try {
Statement stmt = conn.createStatement();
String query = "Select * FROM chemicallist where name_of_reagent like '%" + str + "%'";
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
rs = stmt.executeQuery(query);
while (rs.next()) {
String qty = null, qtyunit = null, chemstate = null, reagentName = null;
reagentName = rs.getString("name_of_reagent");
qty = rs.getString("quantity");
qtyunit = rs.getString("quantity_unit");
chemstate = rs.getString("state");
chemicalTable.getModel().setValueAt(reagentName, count, 0);
chemicalTable.getModel().setValueAt(qty + " " + qtyunit, count, 1);
chemicalTable.getModel().setValueAt(chemstate, count, 2);
if (count + 1 > chemicalTable.getRowCount() - 1) {
dm.setRowCount(chemicalTable.getRowCount() + 1);
dm.fireTableRowsInserted(0, 5);
}
count++;
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error Occurred.", "Error", JOptionPane.ERROR_MESSAGE);
}
My problem is: Whenever I sort first any columns (col1, col2, or col3) and I insert a character in the searchbox, I got this error message:
"Exception occurred during event dispatching:
Java.lang.NullPointerException"
Although it's not possible to debug your code fragments, several things stand out:
In the same section, you reference the TableModel as dm and chemicalTable.getModel(); use a single reference or verify that they refer to the same instance.
Instead of meddling with setRowCount(), use one of the addRow() methods.
The DefaultTableModel methods that alter the model fire the correct event for you and the table will automatically update itself accordingly; you shouldn't have to do this yourself.

How to update values of a row in a table after polling for new incoming data in a loop

I had already implemented polling for this database in java and reads all incoming data which resides in the outgoingqueue. Now I have problems in updating the polled rows, which is like I just change some values in rows, So
My question is :
1.How to loop for the rows in this table such that it has the value of ACTION=804 and has the highest SEQ value.
2.How to update the rows by just changing the values in KEYINFO1 & KEYINFO2 for the table below.
http://imageshack.us/photo/my-images/24/updatinganamolies.png/
Here is the code which does polling and checks for new incoming message
public void run() { // run method calls the fullpoll()
int seqId = 0;
while(true) {
List<KamMessage> list = null;
try {
list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingQueue.addAll(list);
this.outgoingQueue = incomingQueue;
System.out.println("waiting 3 seconds");
System.out.println("new incoming message");
Thread.sleep(3000);
MessageProcessor processor = new MessageProcessor() {
#Override
public void run() {
generate(dbConnection);
}
};
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public List<KamMessage> fullPoll(int lastSeq) throws Exception {
Statement st = dbConnection.createStatement();
ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 and
SEQ >" + lastSeq + "order by SEQ DESC");
List<KamMessage> pojoCol = new ArrayList<KamMessage>();
try {
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KpiMessage pojoClass : pojoCol) {
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + pojoClass.getKeyInfo1());
System.out.print(" " + pojoClass.getKeyInfo2());
System.out.println(" " + pojoClass.getEntryTime());
}
} finally {
rs.close();
st.close();
// TODO: handle exception
}
So here is my example code which am using for generating a row, but how to update this row by having the condition such that it has highest SEQ and ACTION value=804
public void generate()
{
KpiMsg804 upd= createKpiMsg804();
while(true){
try {
st = conn.createStatement();
System.out.println("Updating Values");
String query = "insert into
msg_new_to_bde(tablename,action,keyinfo1,keyinfo2) values(?, ?, ?, ?)";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setString(1,upd.getTableName());
pstmt.setInt(2,upd.getAction()); // set value of action
pstmt.setString(3,upd.getKeyInfo1()); // set key-info value1
pstmt.setString(4,upd.getKeyInfo2()); // set key-info value2
int rows = pstmt.executeUpdate();
System.out.println("Number of Rows Created " +rows);
// execute insert statement
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public KpiMsg804 createKpiMsg804()
{
KpiMsg804 msg= new KpiMsg804();
msg.setKeyInfo1("ENTITYKEY2");
msg.setKeyInfo2("STATUSKEY2");
return msg;
}
how to update by just changing two values in a table for the row in sequence, by changing ENTITYKEY and STATUSKEY to ENTITYKEY1 and STATUSKEY1
I have to use a logic such that my method should look for a row with highest sequence number and corresponding ACTIONKEY, finally it updates(changes the value in) the row with a different value.
P.S : "Kind request : Pls give a reason for giving negative marks (thumbs down) . So that I can explain my question clearly"

Categories

Resources