try {
DataBase DB = new DataBase();
Connection con = DB.Connect();
String sql;
sql = "select Id,Name,FatherName, City, Address, Department,RStatus, DatePlacement\n"
+ "from ECL where "
+ "id like ? and "
+ "name like ? and FatherName like ? and "
+ "City like ? and Address like ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "%" + SearchId.getText() + "%");
pst.setString(2, "%" + SearchName.getText() + "%");
pst.setString(3, "%" + SearchFatherName.getText() + "%");
pst.setString(4, "%" + SearchCity.getText() + "%");
pst.setString(5, "%" + SearchAddress.getText() + "%");
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int MetaColum = rsmd.getColumnCount(); //adding colums in Jtable
Vector col = new Vector();
for (int i = 1; i <= MetaColum; i++) {
col.addElement(rsmd.getColumnName(i));
}
ReTable.setColumnIdentifiers(col);
while (rs.next()) {
Vector rows = new Vector(); // to add rows in Jtable
for (int j = 1; j <= MetaColum; j++) {
rows.addElement(rs.getString(j));
}
ReTable.addRow(rows);
ResultTable.setModel(ReTable);
}
} catch (Exception ex) {
System.out.println(ex);
}
ReTable.fireTableDataChanged(); // Method to refresh the Jtable
}
how to refresh jtable with new data. it loads new data but it also contain the old data every time i search for new name it give me the correct result but the previous search data also remains in jtable. my question is how to refresh jtable every time i make a new search. Thanks In Advance.
You are not removing the previous rows inserted in your model ReTable. In each call you are adding more and more rows in this line:
ReTable.addRow(rows);
Remove all rows from the model before launching the query or create a new model fresh with no rows for each query.
Related
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 (...);
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 ()) {....
I am using PhpMyAdmin to save my data in database. I have a SWT table to populate with database content.
here is my code..
public static void fetchDatafromDB(String StartIndex, String FinalIndex) {
try {
Class.forName(GlobalVariables.SQL_driver).newInstance();
Connection conn = DriverManager.getConnection(GlobalVariables.DB_url + GlobalVariables.DB_name, GlobalVariables.DB_Username, GlobalVariables.DB_password);
Statement st = conn.createStatement();
String query = "SELECT `From`, `To`, `IDno`, `TimeStamp` FROM `callsheet` WHERE TimeStamp BETWEEN '" + StartIndex + "' AND '" + FinalIndex + "'";
ResultSet rs = st.executeQuery(query);
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
// System.out.print(rs.getString(i));
item.setText(i, rs.getString(i));
}
// System.out.println();
}
} catch (Exception P) {
P.printStackTrace();
}
}
it worked.
Now I am getting some problem with tabling the DB content in my swt table. What my program does, is that, it sets the selected (defined by limit in program above) content of DB in one row (one by one manner) but I want the next row of DB table to be tabled in next row of SWT table. Could you suggest something about this? ! Screenshot of my swtTable
It should look something like this:
public static void fetchDatafromDB(String startIndex, String finalIndex) {
try {
Class.forName(GlobalVariables.SQL_driver).newInstance();
Connection conn = DriverManager.getConnection(GlobalVariables.DB_url + GlobalVariables.DB_name, GlobalVariables.DB_Username, GlobalVariables.DB_password);
Statement st = conn.createStatement();
String query = "SELECT `FROM`, `To`, `IDno`, `TimeStamp` FROM `callsheet` WHERE TimeStamp BETWEEN '" + startIndex + "' AND '" + finalIndex + "'";
ResultSet rs = st.executeQuery(query);
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
TableItem item;
while (rs.next()) {
// Create a new TableItem for each entry in the result set (each row)
item = new TableItem(table, SWT.NONE);
for (int i = 1; i <= columnsNumber; i++) {
// Populate the item (mind the index!!)
item.setText(i - 1, rs.getString(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I have this code:
try {
Integer user = InformationService.authenticate(username, password, connection);
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC");
System.out.println("SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC");
while (rs.next()) {
Task p = new Task(rs.getString("title"), rs.getInt("id"), rs.getString("descriere"),
rs.getString("data"), rs.getInt("uid"), rs.getString("data_creare"), rs.getString("ora"),
rs.getInt("status"), rs.getString("priority"), rs.getInt("sters"), rs.getInt("id_parinte"),
rs.getInt("notify"), rs.getString("assigner"), rs.getInt("durata"), rs.getInt("project_id"));
System.out.println(p);
tasks.add(p);
}
The problem is that it returns only the first row, and if I run the query manually I get more results (16 total). Here's the output:
SELECT * FROM tasks WHERE uid = 4 ORDER BY title ASC
models.Task#164b9b8f
Any idea why this is happening?
May be you can improve the code a bit like below which will help you to quickly identify the issue.
int rowCount = 0;
try {
Integer user = InformationService.authenticate(username, password, connection);
Statement st = connection.createStatement();
String query = "SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC";
System.out.println(query);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
Task p = new Task(rs.getString("title"), rs.getInt("id"), rs.getString("descriere"),
rs.getString("data"), rs.getInt("uid"), rs.getString("data_creare"), rs.getString("ora"),
rs.getInt("status"), rs.getString("priority"), rs.getInt("sters"), rs.getInt("id_parinte"),
rs.getInt("notify"), rs.getString("assigner"), rs.getInt("durata"), rs.getInt("project_id"));
rowCount++;
System.out.println(rowCount + "." + p);
tasks.add(p);
}
} finally {
System.out.println("Number of records = " + rowCount);
}
In this approach you can clearly identify how many rows were iterated.
I am using netbeans IDE. I like to check how canni actually search from a jtable which is mapped to a table using netbeans binding. I want to refresh the jtable showing records that matches my search criteria
DefaultTableModel model = new DefaultTableModel( results from your search );
table.setModel( model );
Edit: See Table From Database.
First i get the field names in a Jcombo box.
private void Text1KeyReleased(java.awt.event.KeyEvent evt) {
JTetclear();
Connection con = null;
Statement stmt = null;
try {
con = javaconnect.MySqlServer();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM `" + Combo1.getSelectedItem() + "` where `" + Combo2.getItemAt(0).toString() + "` Like '%" + Text1.getText() + "%' or `" + Combo2.getItemAt(1).toString() + "` Like '%" + Text1.getText() + "%' or `" + Combo2.getItemAt(2).toString() + "` Like '%" + Text1.getText() + "%' or `" + Combo2.getItemAt(0).toString() + "` Like '%" + Text1.getText() + "%' order by PARTNO;");
ResultSetMetaData md = rs.getMetaData();
DefaultTableModel tm = (DefaultTableModel) Table1.getModel(); // for changing column and row model
Combo2.removeAllItems();
tm.setColumnCount(0); tm.setRowCount(0); // clear existing columns and clear existing rows
for (int i = 1; i <= md.getColumnCount(); i++) {
tm.addColumn(md.getColumnName(i));
Combo2.addItem(md.getColumnName(i));//l load the column name in the combobox
}
tm.setRowCount(0); // clear existing rows
while (rs.next()) { // Get row data
Vector row = new Vector(md.getColumnCount());
for (int i = 1; i <= md.getColumnCount(); i++) {
row.addElement(rs.getObject(i));
}
tm.addRow(row);
Table1.getColumnModel().getColumn(0).setPreferredWidth(160);
Table1.getColumnModel().getColumn(1).setPreferredWidth(380);
}
rs.close();
stmt.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex, ex.getMessage(), WIDTH, null);
}
}
This is how i did it. Not an expert.
A method that returns result set:
public ResultSet actualInventoryInCencos(int idCencos) throws SQLException {
try {
SQL sql = new SQL();
PreparedStatement selectPS = sql.createPStatement(cf.SELECT_INVENTORY_BY_CENCOS);
selectPS.setInt(1, idCencos);
ResultSet resultSet = selectPS.executeQuery();
return resultSet;
} catch (SQLException | NullPointerException e) {
System.out.println(cf.ERROR_SQL + e);
cf.e(1);
return null;
}
}
Method in TableDAO that accepts the result set and make and returns a DefaultTableModel with all the query data.
public DefaultTableModel createTable(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
//ColumnsNames
Vector<String> columnsNames = new Vector<>();
columnsNames.add("Column1");
columnsNames.add("Column2");
columnsNames.add("Column3");
Vector<Vector<Object>> tableData = new Vector<>();
while (rs.next()) {
Vector<Object> vector = new Vector<>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
tableData.add(vector);
}
return new DefaultTableModel(tableData, columnsNames);
}
And the line to set the New Model to your JTable:
yourJTable.setModel(tableDAO.createTable(inventory.actualInventoryInCencos(userData.getUserId())));