Adding Data from database to custom jtable - java

I am trying to add the databases to specific column,row the column always is the same but the row change. So I enter the variable and trying to add one to the number but not luck all is printing are 0 so is not adding any number to the variable for that reason my table stay in the same row and never change. I try i++; i=i+1; all I have is 0 on the println(). Im using Netbeans.
Statement stmt = null;
String sql="select * from gateway where date= "+id;
try{
Connect conn=new Connect();
stmt = conn.makeStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
int i=0;
Object ids = rs.getString("Business");
Object items = rs.getString("GatewayJob");
Object descriptions = rs.getString("Status");
Object quantitys = rs.getString("Timework");
Object price = rs.getString("Notes");
jTable1.getModel().setValueAt(ids,i, 0 );
jTable1.getModel().setValueAt(items, i, 1);
jTable1.getModel().setValueAt(descriptions, i, 2);
jTable1.getModel().setValueAt(quantitys, i, 3);
jTable1.getModel().setValueAt(price, i, 4);
System.out.println(i);
i++;
}

In you code
while(rs.next()) {
int i=0;
move the int i = 0; to before your while loop
this statement will reset i back to 0 everytime

Don't use the setValueAt() method. This implies you have loaded the TableModel with a bunch of rows containing null values which is a bad design as you don't know how many rows the query will return.
Instead, you should be dynamically building the TableModel by adding a new row to the model in your loop.
See Table From Database, especially the Table From Database Example code for a simple solution that uses the DefaultTableModel.

try this code. im using String connection. this codes is running.
String sql = "select * from tblstudent";
try{
database.Query(sql);
int inc=0;
while(database.dataTable.next()){
Object a = database.dataTable.getInt("StudentID");
Object b = database.dataTable.getString("Firstname");
Object c = database.dataTable.getString("Lastname");
Object d = database.dataTable.getString("Gender");
Object e = database.dataTable.getInt("CourseID");
tblStudent.getModel().setValueAt(a, inc, 0 );
tblStudent.getModel().setValueAt(b, inc, 1);
tblStudent.getModel().setValueAt(c, inc, 2);
tblStudent.getModel().setValueAt(d, inc, 3);
tblStudent.getModel().setValueAt(e, inc, 4);
inc++;
}
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null, "Error");
}
}

Because i is reset to 0 every while loop.So you should put int i=0; before while().
int i=0;
while(rs.next()){
...
}

Related

Using PreparedStatement to sort records in MySQL

Im trying to write a code in which when a user will click an a "Sort by Name" button, my program will sort the records of my Database and put them in a JTable,combining 2 DB Tables with INNER JOIN. I have managed to do this by using a resultSet and selecting for example Ascending Order. But because I dont want to have 2 buttons, one for the ASC and one for the DESC, I thought of using preparedStatement and an showInputDialog in which the user will select if he wants to have an ASC or a DESC ordering and execute the order. Also, I remembered that some programs I've seen used a feature in which the first time you clicked the button it sorted DESC and if you pressed it again would order by ASC(havent managed to find in on the WEB).About my first thought, I tried to do it but I could get past this one
ResultSetMetaData mdsort = rssort.getMetaData();
I should have an ResultSet variable(rssort) to use getMetaData() but if I selected to make the program with my PreparedStatement i would get an error there. Any suggestions??
try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
Statement stmtsort = conn.createStatement();
ResultSet rssort = stmtsort.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id ORDER BY consoles.name ASC");
// ERROR HERE!!! needs resultset,not preparedStatement
ResultSetMetaData mdsort = rssort.getMetaData();
columnCount = mdsort.getColumnCount();
String[] colssort = new String[columnCount];
for (i=1;i<= columnCount;i++)
{
colssort[i-1] = mdsort.getColumnName(i);
}
DefaultTableModel model = new DefaultTableModel(colssort,0);
while (rssort.next())
{
Object[] rowsort = new Object[columnCount];
for (i = 1 ; i <= columnCount ; i++)
{
rowsort[i-1] = rssort.getObject(i);
}
model.addRow(rowsort);
}
JTable table = new JTable(model);
model.fireTableDataChanged();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(218,59,529,360);
frame.getContentPane().add(table);
model.fireTableDataChanged();
conn.close();
stmtsort.close();
rssort.close();
} catch (SQLException case1)
{case1.printStackTrace();
} catch (Exception case2)
{case2.printStackTrace();}
}
});
UPDATE
OK I managed to fix this issue with the getMetaData() but now the thing is that I dont use any ResultSet variables/instances and cant use next() method to create my DB.
String name = "SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id ORDER BY consoles.name ?";
PreparedStatement psname = conn.prepareStatement(name);
String strin = JOptionPane.showInputDialog(null,"ASC or DESC order ? : ");
psname.setString(1,strin);
psname.executeUpdate();
ResultSetMetaData mdsort = psname.getMetaData();
int columnCount = mdsort.getColumnCount();
.
.
.
// error coming up here,because i deleted the ResultSet
while (psname.next())
.
.
.
Better make a bit more complex TableModel.
That is more optimal.
Keep the data from the ResultSet in an original TableModel.
Use a wrapping TableModel to sort, and maybe filter.
Use the ResultSetMetaData for the column type, if it is Number (Integer, BigDecimal, ...) then use that type instead of Object for the column type: gives a right aligned column.
Maybe first do an internet search for ResultSetTableModel; other peoply must have done it already.
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
String strin = JOptionPane.showInputDialog(null,"ASC or DESC order ? : ");
stmtsortname = conn.createStatement();
rssortname = stmtsortname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id ORDER BY consoles.name "+strin);
mdsortname = rssortname.getMetaData();
columnCount = mdsortname.getColumnCount();
String[] colssortname = new String[columnCount];
for (i=1;i<= columnCount;i++)
{
colssortname[i-1] = mdsortname.getColumnName(i);
}
model = new DefaultTableModel(colssortname,0);
while (rssortname.next())
{
Object[] rowsortname = new Object[columnCount];
for (i = 1 ; i <= columnCount ; i++)
{
rowsortname[i-1] = rssortname.getObject(i);
}
model.addRow(rowsortname);
}
table = new JTable(model);
model.fireTableDataChanged();
table.setCellSelectionEnabled(true);
table.setColumnSelectionAllowed(true)
table.setFillsViewportHeight(true);
table.setSurrendersFocusOnKeystroke(true);
table.setBounds(146,59,763,360);
frame.getContentPane().add(table);
model.fireTableDataChanged();
conn.close();
stmtsortname.close();
rssortname.close();
} catch (SQLException case1)
{
case1.printStackTrace();
}
catch (Exception case2)
{
case2.printStackTrace();
}
}
});

ResultSet returns only last row into JTable

I have done enough searches to solve my problem which i have done partly but there's this one bug that keeps disturbing me.I am trying to fetch data from a database based on a condition.I have a table 'user_branch' with a foreign key column branchID which is supposed to fetch the coresponding branchNames in another table 'branches' and I am supposed to display the results into a JTable.When i do System.out.println i get all my results but it returns only the last row when i display in a JTable(branchJTable).This is the code i am using
int row = user2BAssignedJTable.getSelectedRow();
assignUserID.setText(user2BAssignedJTable.getModel().getValueAt(row, 0).toString());
user2BAssignedField.setText(user2BAssignedJTable.getModel().getValueAt(row, 1).toString());
try {
String userBrQry = "SELECT branchID FROM user_branch WHERE userID IN(?) ";
String brQ = "SELECT branchName FROM branches WHERE branchID IN(%s) ";
pstmt = con.prepareStatement(userBrQry);
pstmt.setString(1, assignUserID.getText());
results = pstmt.executeQuery();
results.last();
int nRows = results.getRow();
results.beforeFirst();
while (results.next()) {
String branchIDS = results.getString("branchID");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < nRows; i++) {
builder.append("?");
if (i + 1 < nRows) {
builder.append(",");
}
}
brQ = String.format(brQ, builder.toString());
PreparedStatement ps = con.prepareStatement(brQ);
for (int i = 0; i < nRows; i++) {
ps.setString(i + 1, branchIDS);
}
ResultSet rs = ps.executeQuery();
//branchJTable.setModel(DbUtils.resultSetToTableModel(rs));
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
while (rs.next()) {
String branchname = rs.getString("branchName");
model.addRow(new Object[]{branchname});
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Forget about the first 3 rows as it is a another JTable event i use to get the userID to use as a condition for getting a particular user's branches assigned to him.
The branches assigned to a user is dynamic hence using StringBuilder.
I am supposed to display the results into another JTable called branchJTable which only displays the last row.Any HELP would be appreciated!
From your question, I think you should declare the JTable
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
before your first loop -
i.e. before while (results.next()) { in your code.
Otherwise in loop, for each loop execution,
the JTable Model is initialising and you are getting the last inserted row in Jtable.

ArrayList keep returning 0

I retrieve the data from database and loop it thru an array to display the like amount.
public void SetUpLikeAmount() {
int likes = 0;
ArrayList <Integer> likeArray = new ArrayList <Integer>();
for (int count = 0; count < likeArray.size();count++){
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes from forumLikeDislike WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likeArray.add(Integer.parseInt(resultSet.getString("likeDislike_likes")));
likes += likeArray.get(count);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
}
jLabel_like.setText(Integer.toString(likes));
}
However, it keeps returning 0. Thanks in advance.
(As an aside, it never returns anything - you've posted a void method.)
Look at this code:
ArrayList <Integer> likeArray = new ArrayList <Integer>();
for (int count = 0; count < likeArray.size();count++){
...
}
You've just created a new ArrayList<Integer>, which will therefore have a size of 0. Therefore, the loop always completes immediately, without ever executing the body.
If you're trying to get input from a list created elsewhere, you should probably pass that into your method. (You should also use a PreparedStatement with a parameter instead of including the value directly in your SQL.)
You're iterating over the list likeArray which is empty. So it won't enter the loop
May be here is the new code you should refer:
public void SetUpLikeAmount() {
int likes = 0;
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes from forumLikeDislike WHERE topic_id = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likes += Integer.parseInt(resultSet.getString("likeDislike_likes"));
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
jLabel_like.setText(Integer.toString(likes));
}
You might not need the arraylist I believe as you are getting the value and summing it during the iteration over the result set only.

Comparison between two ResultSet in Java

What is the best way to handle Java ResultSet? I'm creating a Desktop application that will connect to an oracle database using JDBC.
However, I am having problem with handling ResultSets since I can't do comparison using for loop.
// create a database connection object
DB db = new DB();
// get rows of my first table and second table
ResultSet firstRS = db.getMyFirstTable();
ResultSet seconRS = db.getSecondTable();
// compare the two tables
while(firstRS.next())
{
// get the row of my first table
String firstRSRow = firstRS.getString("col1");
while(secondRS.next())
{
// get the row of my second table
String secondRSRow = seconRS.getString("col1");
// compare row from first table to the row in second table
if(firstRSRow.startsWith(secondRSRow))
{
// do some processing here....
} // end if
} // end while
} // end while
I know that this could be accomplish with Hibernate with a few lines of code but I don't have the luxury of time to study it.
I also found commons DbUtils from apache but it seems complicated for me as a novice programmer.
Is there other way/tools/libraries/framework simple enough to get ResultSet from databases and manipulate it in simple and straightforward manner?
I will also appreciate if you could direct me to a website that has sample codes concerning java database connectivity.
Thank you very much for your support.
Why ResultSet? You could easily compare values with SELECT statement. In case you still want to ResultSet then think about CachedRowSet.
DB db = new DB();
// get rows of my first table and second table
ResultSet firstRS = db.getMyFirstTable();
ResultSet seconRS = db.getSecondTable();
// compare the two tables
while(firstRS.next() || secondRS.next())
{
// get the row of my first table
String firstRSRow = firstRS.getString("col1");
String secondRSRow = seconRS.getString("col1")
// compare row from first table to the row in second table
if(firstRSRow.startsWith(secondRSRow))
{
// do some processing here....
} // end if
} // end while
public static boolean resultset(String SQL1, String SQL2){
public boolean status=false;
ResultSet ViewResultset = st.executeQuery(SQL1);
ResultSet QueryResultset = st.executeQuery(SQL2);
while (QueryResultset.next() | ViewResultset.next())
if (ViewResultset.getRow() == 0 | QueryResultset.getRow() == 0) {
break;
} else {
for (int i = 1; i < ViewResultset.getMetaData().getColumnCount() + 1; i++) {
System.out.println("OOO"+ QueryResultset.getMetaData().getColumnCount());
String columnName = ViewResultset.getMetaData().getColumnName(i);
System.out.println("ColumnName :" + columnName);
for (int j = 1; j < QueryResultset.getMetaData().getColumnCount() + 1; j++)
if (ViewResultset.getMetaData().getColumnName(i).equals(QueryResultset.getMetaData().getColumnName(j))&& !(QueryResultset.getString(columnName) == null || ViewResultset.getString(columnName) == null))
if (ViewResultset.getString(columnName).toUpperCase().contains(QueryResultset.getString(columnName).toUpperCase())) {
System.out.println(" Actual "+ ViewResultset.getMetaData().getColumnName(i) + " Expected: "+ ViewResultset.getString(columnName));
status=true;
}
else {System.out.println(" Actual "+ ViewResultset.getMetaData().getColumnName(i) + " Expected: "+ ViewResultset.getString(columnName));
}
}
}
return status;
}
}
ResultSet is a subclass of Object ultimately and we can compare two or more objects directly. A little specific to your question:
ResultSet rs=st.executeQuery(sql1);
ResultSet rs1=st.executeQuery(sql2);
where sql1 and sql2 are 2 Statements
while(rs.next() && rs1.next()){
int a=rs.next();
int b=rs1.next();
if(a==b){
System.out.println("Compairing two ResultSets");
}
}

getColumnCount does not count the column when its value is null?

I have this code:
// Get the results
while(rs.next())
{
resultList = new JSONObject();
for(int i = 1; i <= rsmd.getColumnCount(); i++)
{
resultList.put(rsmd.getColumnName(i) , rs.getString(i));
}
}
It appears that rsmd.getColumnCount() does not count the columns for which the corresponding value is null. Is there any workaround for this ?
Depending on the time of the day, the same SQL returns values and/or nulls and I would like to get the same number of columns each time.
Cheers,
Tim
This is JAVA of course - and I used the "Null" tag because the getColumnCount tag was refused because I am lacking "reputation points" on this site.
I think getColumnCount is not counting the null entries because I have 2 entries in my DB, one with a few null entries and the other one with no null entries.
getColumnCount only returns the count for entries with actual values.
Problem solved: The problem was not getColumnCount(), but the
resultList.put(rsmd.getColumnName(i) , rs.getString(i));
The Put method did not add anything when rs.getString(i) returned null.
What induced me into error was that a print of these values did show the null.
Did you try to put some flag on your query? If it's null then put something and you can catch these on your code.
I have a similar problem, but it is not related to nulls, I just get a totally wrong answer back from getColumnCount(). My workaround uses a separate ResultSet, thusly:
// Get the results
DatabaseMetaData metadata = null;
ResultSet rs = null;
int columnCount = 0;
try {
metadata = connection.getMetaData();
rs = metadata.getColumns(null, "YOURSCHEMA", "YOURTABLE", null);
while (column.next()) {
columnCount++;
}
} catch (Exception e) {
e.printStackTrace();
}
/* note here you must re-fill your rs or create a new one since it cannot be reset
with a call to rs.first() as it is a forward-only collection, with something like */
// rs = statement.executeQuery("SELECT * FROM yourschema.yourtable");
while(rs.next())
{
resultList = new JSONObject();
for(int i = 1; i <= rsmd.getColumnCount(); i++)
{
resultList.put(rsmd.getColumnName(i) , rs.getString(i));
}
}

Categories