When I am typing in jtable row I need to get suggestions to that table rows(filtered) from mysql data base and select from it (like Invoice generating as picture )I need to develop as below picture and here is the code I coded so far
jdbc j = new jdbc();
DefaultTableModel dt = (DefaultTableModel) tab_reta_in.getModel();
int row = tab_reta_in.getSelectedRow();
int col = tab_reta_in.getSelectedColumn();
Data_feild = (String) tab_reta_in.getValueAt(row, col);
int Def_r = row;
if (col == 0) {
try {
ResultSet rs = j.GetData("select * from invoice_retails where name like '" + Data_feild + "%' ");
while (rs.next()) {
String col0 = rs.getString("medi_id");
String col1 = rs.getString("name");
String col2 = rs.getString("prize");
Object[] rows = {col0, col1, col2};
dt.addRow(rows);
}
} catch (Exception ex) {
System.out.println(ex);
}
Related
I want to display some students fees track on a JFrame when a jbutton is clicked after typing the StudentID in a jTextField.
The student data is stored in MySQL Db, the table studentrolls contains info about the students with STRollID as Primary Key and StudentID, BachID as Foreign Key and the table fees contain all students fee record of past years and actual year with STRollID as Primary Key and BachID as Foreign Key.
I want to display after inserting the StudentID on a jTextField and clicking a jButton only actual year fee if a jCheckBoxonlythisyearfee is selected, otherwise, the frame will display all the fee record on a jTable and on some jLabels.
I wrote this code, I am not getting any error but when I run the file, I'm getting all the student fee records but when I'm clicking on the jCheckBoxonlythisyearfee nothing is happening am not getting only this year fee record.
Is there anything wrong with my code? Please help.
private void rSButtonIconDsearchstidActionPerformed(java.awt.event.ActionEvent evt) {
try {
Date d = new Date();
int year = d.getYear();
int currentYear = year + 1900;
boolean thisyrchecboxisSelected = jCheckBoxonlythisyearfee.isSelected();
String sqlquerystfeeslist;
if (thisyrchecboxisSelected) {
sqlquerystfeeslist = "SELECT * FROM studentrolls, fees WHERE studentrolls.StudentID = ? AND studentrolls.STRollID = fees.STRollID AND studentrolls.BachID = '"
+ currentYear + "' ORDER BY studentrolls.BachID";
} else {
sqlquerystfeeslist = "SELECT * FROM studentrolls, fees WHERE studentrolls.StudentID = ? AND studentrolls.STRollID = fees.STRollID ORDER BY studentrolls.BachID";
}
PreparedStatement preparedStatement = con.prepareStatement(sqlquerystfeeslist);
PreparedStatement pst = con.prepareStatement(sqlquerystfeeslist);
if (!jTextFieldsearchstid.getText().isEmpty()) {
preparedStatement.setString(1, jTextFieldsearchstid.getText());
ResultSet resultSet = preparedStatement.executeQuery();
DefaultTableModel tblModelfee = (DefaultTableModel) jTablestfeeslist.getModel();
tblModelfee.setRowCount(0); // to clear the table before inserting new data
while (resultSet.next()) {
int stfeebalenceint;
int feecostint = Integer.parseInt(resultSet.getString("MontantFrais"));
int paidamountint = Integer.parseInt(resultSet.getString("MontantPayE"));
stfeebalenceint = feecostint - paidamountint;
String feestatus;
if (stfeebalenceint <= 0) {
feestatus = "SOLDE";
} else {
feestatus = "NO SOLDE";
}
String scolaryearfee = resultSet.getString("BachID");
String feetype = resultSet.getString("TypeFrais");
String feecost = String.valueOf(resultSet.getInt("MontantFrais"));
String paidamount = String.valueOf(resultSet.getInt("MontantPayE"));
String stfeebalence = String.valueOf(stfeebalenceint);
String stfeeslistTableData[] = {scolaryearfee, feetype, feecost, paidamount, stfeebalence, feestatus};
tblModelfee.addRow(stfeeslistTableData);
int stTotfeecost = 0;
for (int i = 0; i < jTablestfeeslist.getRowCount(); i++) {
stTotfeecost = stTotfeecost + Integer.parseInt(jTablestfeeslist.getValueAt(i, 2).toString());
}
int stTotpaidamount = 0;
for (int i = 0; i < jTablestfeeslist.getRowCount(); i++) {
stTotpaidamount = stTotpaidamount + Integer.parseInt(jTablestfeeslist.getValueAt(i, 3).toString());
}
int stTotfeebalence;
stTotfeebalence = stTotfeecost - stTotpaidamount;
String stTotfeestatus;
if (stTotfeebalence <= 0) {
stTotfeestatus = "SOLVABLE";
} else {
stTotfeestatus = "INSOLVABLE";
}
jLabelstTotfeecost.setText(Integer.toString(stTotfeecost));
jLabelstTotpaidamount.setText(Integer.toString(stTotpaidamount));
jLabelstTotfeebalence.setText(Integer.toString(stTotfeebalence));
jLabelstTotfeestatus.setText(stTotfeestatus);
}
} else {
JOptionPane.showMessageDialog(this, "Veillez taper le matricule d'un eleve svp.");
}
} catch (Exception exception) {
JOptionPane.showMessageDialog(this, "erreur des donnees: " + exception.getMessage());
}
}
Here is code, i am using 2 jdatechooser and i put the codes in a button. I am also not sure if the query is correct.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://USER-PC:1433;databaseName=tblgg";
String userr="sa";
String passs="1234";
Connection con=DriverManager.getConnection(url,userr,passs);
java.util.Date first = dt1.getDate();
java.util.Date second = dt2.getDate();
String sql="SELECT * FROM tbl_sale WHERE date between '"+ first+"'and
'"+second+"'";
PreparedStatement pst= con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
tblsale.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
Okay i edit my code. xD now something is happening but nothing is showing up.
To correct your lack of prepared statement usage. Try this
Resuse your connection
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://USER-PC:1433;databaseName=tblgg";
String userr="sa";
String passs="1234";
Connection con=DriverManager.getConnection(url,userr,passs);
ResultSet result = null;
String sql2 = "select\n" +
"*\n" +
"from student\n" +
"where date(first) > ? and date(second) < ?";
PreparedStatement ps1 = con.prepareStatement( sql2, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY) ;
ps1.setObject (1 , startDatePicker.getModel().getValue());
ps1.setObject (2 , endDatePicker.getModel().getValue());
result = ps1.executeQuery();
// get number of rows
result.last();
numRows = result.getRow();
result.first();
//Get metadata object for result
ResultSetMetaData meta = result.getMetaData();
// create an arry of string for the colum names
colNames = new String[meta.getColumnCount()];
// store column names in the new col names array
for( int i = 0; i< meta.getColumnCount(); i++)
{
//get column name
colNames[i] = meta.getColumnLabel(i+1);
}
// create 2 d string array for table data
tableData = new String [numRows][meta.getColumnCount()];
// store columns in the data
for ( int row = 0 ; row < numRows; row++)
{
for (int col = 0; col < meta.getColumnCount(); col++)
{
tableData[row][col]= result.getString(col + 1);
}
result.next();
}
// close statement
ps1.close();
connection.close();
System.out.println("Data Table Loaded.");
}
To show the created result data set you use these lines
JTable table = new JTable(tableData,colNames);
JScrollPane scrollPane = new JScrollPane(table);
Don't forget to add the scroll pane to your JPanel
panel.add(scrollPane);
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();
}
}
As mentioned in the header I cannot get my JTable to update with a new row unless I restart the program. When I restart, the new row is there and everything is as it should be. I have tried revalidating/repainting the panel and frame, I have tried the fire methods. I'm at a loss. Thanks in advance
ActionListener (in adminGUI class) for 'Add' button:
if(source.equals(add2)){
String c = itb.getText();
int a = main.getResults();
boolean matches = Pattern.matches("[A-Z][a-z]+", c);
if(matches == true){
main.addGenre(a, c);
}
String Method(in main class) to add a row to the database table:
public static void addGenre(int a, String b){
int rowsAdded;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect =DriverManager.getConnection("jdbc:odbc:MovieDB");
Statement stmt = connect.createStatement();
String query = "INSERT INTO Genres (genre_id, genre_name)" + "VALUES(" + a + ", '" + b + "')";
rowsAdded = stmt.executeUpdate(query);
}catch(Exception exc){}
}
Method(also in main class) to increment the auto-increment-key column:
public static int getResults(){
int a = 0;
ResultSet ints = main.getResults("Select genre_id from Genres");
try {
while(ints.next()){
int d = ints.getInt("genre_id");
if(d>a){
a = d;
}
a++;
}
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
return a;
}
JTable details:
ResultSet rs1 = main.getResults("Select * from Genres");
JTable tab1 = new JTable(DbUtils.resultSetToTableModel(rs1));
DbUtils.resultSetToTableModel details :
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
"I cannot get my JTable to update with a new row unless I restart the program."
I think what you're expecting is that when the database table update, so should your JTable. It doesn't really work like that. You need to update the TableModel, and the JTable will be automatically updated
Since resultSetToTableModel returns a DefuaultTableModel, you can use either of the two methods from DefaultTableModel:
public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So when your are adding the data to the database, you also want to update the DefaultTableModel like this
public static void addGenre(Integer a, String b){
...
rowsAdded = stmt.executeUpdate(query);
if (rowsAdded > 0) {
DefaultTableModel model = (DefaultTableModel)tab1.getModel();
model.addRow( new Object[] { a, b });
}
}
Also noticed I changed the method signature to Integer instead of int so it will fit with the Object[] passed to addRow. The int you pass to it will get autoboxed to Integer
SIDE NOTES
Don't swallow you exception by putting nothing in the catch block. Put something meaningful that will notify you of any exceptions that may occur, like
catch(Exception ex) {
ex.printStackTrace();
}
You should also close your Connections, Statements, and ResultSets
You should use PreparedStatement instead of Statement, to avoid SQL injection.
private void resetListData() throws ClassNotFoundException, SQLException
{
Connection cne = null;
try {
Class.forName("org.sqlite.JDBC");
cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
cne.setAutoCommit(false);
PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from Genres");
psd.execute();
ResultSet r = psd.getResultSet();
ResultSetMetaData rsmd = r.getMetaData();
int count = rsmd.getColumnCount();
String[] meta = new String[count];
for (int i = 0; i < count; i++)
{
String name = rsmd.getColumnName(i + 1);
meta[i] = name;
//System.out.println(name);
}
model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
jTable1.setModel(model);
while (r.next())
{
Object[] row = new Object[count];
for (int i = 1; i <= count; ++i)
{
row[i - 1] = r.getString(i); // Or even rs.getObject()
}
model.addRow(row);
}
cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}
Use this code. so you can insert one row at the end of Jtable without restarting application.,
Thanks..
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())));