I'm totally new to programming and not really good with it. This is my first question in stack overflow. I'm doing a project where I use java swing to develop a hotel management desktop application. I need help on displaying data from 2 sql tables to a single jtable.I have created a method for that.A positive response is appreciated :). The code is stopped in the while loop and gives fail as output.
The code will be as follows:
public void displayTable(){
try{
String sql = "SELECT customer.Cid,customer.Cname,customer.CEmail,customer.CContact,Reservation.checkIn,Reservation.checkOut from customer,Reservation where customer.Cid = Reservation.CusID";
System.out.println("done");
PreparedStatement pst;
pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
System.out.println(jTable1);
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
List<itp.reservation.model.ReservationDetails> arrList = new ArrayList<itp.reservation.model.ReservationDetails>();
List<itp.reservation.model.CustomerDetails> arList = new ArrayList<itp.reservation.model.CustomerDetails>();
System.out.println("new done");
while(rs.next())
{
System.out.println("lev");
itp.reservation.model.CustomerDetails x = new itp.reservation.model.CustomerDetails();
//itp.reservation.model.ReservationDetails y = new itp.reservation.model.ReservationDetails();
System.out.println("qwe");
x.setCid(rs.getString(1));
x.setCname(rs.getString(2));
x.setCemail(rs.getString(3));
x.setCcontact(rs.getInt(4));
System.out.println("new");
//y.setCheckin(rs.getDate(5));
//y.setCheckout(rs.getDate(6));
System.out.println("restable");
//arrList.add(y);
arList.add(x);
}
jTable1.setModel(model);
}catch(Exception e){
System.out.println("Fail");
}
}
Related
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);
}
}
I have two classes, the first is the GUI which has jTable, and the other one for querying database.
Adding rows to the table within the same class works fine. I used this way:
((DefaultTableModel) table.getModel()).addRow(values);
While values is a Object[] holding the row content.
This is working fine. But populating has to be done from another class. So I have in the query class:
((DefaultTableModel) rg.table.getModel()).addRow(values);
While rg is an object of the GUI class. And table is public.
This doesn't do anything not even throwing an exception.
What should I change in my query class? Here's my method in the query class:
public void selectPassengers(int rows) {
PreparedStatement pst = null;
ResultSet rs = null;
String query = "SELECT * FROM brs.passenger";
try {
pst = con.prepareStatement(query);
rs = pst.executeQuery();
Object[] attributes = new Object[9];
Register rg = new Register();
while (rs.next()) {
attributes[0] = String.valueOf(rs.getString(1));
attributes[1] = rs.getString(2);
attributes[2] = rs.getString(3);
attributes[3] = rs.getString(4);
attributes[4] = rs.getString(5);
attributes[5] = rs.getString(6);
attributes[6] = rs.getString(7);
attributes[7] = rs.getString(8);
attributes[8] = rs.getString(9);
((DefaultTableModel) rg.table.getModel()).addRow(attributes);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Fetching data from the DB is fine. I could print them to the console.
jTable is I assume is built correctly. I can tell this because I
can insert rows correctly but only within the GUI class itself (the
class where jTable is there).
Moving the inserting logic to a different class (querying class) is
where I am stuck.
I solved this by calling the frame object before the model object.
So instead of rg.model.addRow();, I used rg.frame.model.addRow();, after making frame public in the GUI class.
I am working on my graduation project. I is a Java application that connects to a database. I want to apply search in database with combobox when user select item the result will shows in JTable I wrote the code but I don't know what is wrong with my SQL command it throw this exception
أبر 18, 2016 5:03:32 م MyQuery getData
SEVERE: null
java.sql.SQLException: [Microsoft][?????? ????? ODBC Microsoft Access] ??? ?? ???? ?????? (???? ??????? ?????) ?? ????? ??????? '`CAT_NAME`= Human Resources'.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3109)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:337)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:252)
at MyQuery.getData(MyQuery.java:33)
at Travel1.jComboBoxCat1ActionPerformed(Travel1.java:177)
at Travel1.access$100(Travel1.java:33)
at Travel1$3.actionPerformed(Travel1.java:137)
at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1260)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:588)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:624)
This is my code:
private void jComboBoxCat1ActionPerformed(java.awt.event.ActionEvent evt) {
MyQuery mq = new MyQuery();
ArrayList<Course> list = mq.getData((String)jComboBoxCat1.getSelectedItem());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[]{"Course Name","Duration","FEES","City","Category"});
Object[] row = new Object[5];
for(int i = 0; i < list.size(); i++){
row[0] = list.get(i).getCourse_Name();
row[1] = list.get(i).getDuration();
row[2] = list.get(i).getFEES();
row[3] = list.get(i).getCourse_Date();
row[4] = list.get(i).getCity();
model.addRow(row);
}
jTableresult.setModel(model);
MyQuery Class
public ArrayList<Course> getData(String catName){
ArrayList<Course> list = new ArrayList<Course>();
Connection con = getConnection();
Statement st;
ResultSet rs;
try {
st = con.createStatement();
rs = st.executeQuery("SELECT ` COURSE_NAME`,`DURATION`,`FEES`,`DATE_FROM`,`C_NAME`,CAT_NAME FROM `Course` WHERE `CAT_NAME`= " + catName);
Course p;
while(rs.next()){
p = new Course(
rs.getString("COURSE_NAME"),
rs.getInt("DURATION"),
rs.getInt("FEES"),
rs.getString("DATE_FROM"),
rs.getString("C_NAME"),
rs.getString("CAT_NAME")
);
list.add(p);
}
} catch (SQLException ex) {
Logger.getLogger(Travel1.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
}
This is NOT a Swing problem. It is an SQL problem.
So first you create a method to do an SQL query and return a ResultSet. Then you hard code all the data to get the SQL working. Then you add in the logic that does the dynamic query by getting the search string from the combo box. The idea is to simplify the problem and concentrate on the direct error.
Regarding the problem I have a couple of suggestions:
1) I have never use the quotes around the individual column names so I don't know if they are needed. In any case I would remove the leading spaces before the "Course_Name" in the SQL.
2) Use a PreparedStatement. It allows you to specify parameters for your variables in the SQL string and will then format the SQL using these variables so you don't have to worry about the formatting. A basic example:
String sql = "Select * from SomeTable where SomeColumn = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, someColumnVariable);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
// do something
}
rs.close();
stmt.close();
Your sql statment should look like this
String sql = "Select column_name From table_name Where column_name = 'text';
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?
I am trying to populate a JTable with data from a database. I've tried so many different ways and it just doesn't want to work. Currently I have a class which returns a resultset with the entire database to my UIClass which then uses the resultset to populate the JTable. Bellow is my method that retrieves the resultset and then populates the JTable.
private void SetJTable()
{
int count = 0;
String boatclass, senior, under23, junior;
try
{
ResultSet results = object.AllWorldBestTimes();
DefaultTableModel model = (DefaultTableModel) Times.getModel();
model.addColumn("Boat Class");
model.addColumn("Senior");
model.addColumn("Under 23");
model.addColumn("Junior");
while(count<24)
{
boatclass = results.getString(1);
senior = results.getString(2);
under23 = results.getString(3);
junior = results.getString(4);
System.out.println(boatclass + senior + under23 + junior);
model.insertRow(Times.getRowCount(), new Object[]{boatclass, senior, under23, junior});
count++;
}
Times = new JTable(model);
}
catch (SQLException e)
{
System.out.println("Ef");
}
}
Here is the method of retrieving data from the database:
public ResultSet AllWorldBestTimes() throws SQLException
{
DatabaseConnection connection = new DatabaseConnection();
ResultSet result = connection.SelectStatements("SELECT * FROM WorldBestTimes");
return result;
}
there is no crash so i cannot give the stack trace, nor does it go into the catch statement.
any help would be appreciated!
model.insertRow(Times.getRowCount(), ...
Times.getRowCount() is always going to return zero, since it's empty.
Times = new JTable(model);
Reassigns the reference Times, but it doesn't take the old table out of the form or add the new one into the form.
Try this...
model = new DefaultTableModel();
...and this...
model.insertRow(model.getRowCount(), ...
...and this...
Times.setModel(model);
Hard to say if that will do it or not. The code sample isn't exactly SCCE.