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 want to Count all the rows in the table using java and display the count of all the rows in the textfield. I need the count of employee from the table. I have attached below the code and the query used to achieve this. I received the error of the below code Column 'id' not found. error displayed
public void Customer()
{
try {
pst = con.prepareStatement("SELECT COUNT(*) FROM customer");
ResultSet rs = pst.executeQuery();
while(rs.next())
{
String id1 = rs.getString("id");
txtmsg.setText(id1);
}
} catch (SQLException ex) {
Logger.getLogger(gsm.class.getName()).log(Level.SEVERE, null, ex);
}
}
There clearly is no "id" column in your select. You could either get the result by column number like so:
int count = rs.getInt(1);
Or you could use an alias for the column and get result by that name, eg.:
pst = con.prepareStatement("SELECT COUNT(*) AS customerCount FROM customer");
int count = rs.getInt("customerCount");
I have read notes about this but none seems to work for me. I have an SQLite database and with Netbeans as my IDE, I have a jframe that displays data records in a jtable, with records displayed in ascending order. Clicking on a record displays them in jtextfields.
I want to move to next record in database in ascending order when I click on a button, but it doesn't seem to work. What am I doing wrong?
try{
String sql ="select * from Employees order by Name ASC";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
int i = rs.getInt("ID");
String idi= Integer.toString(i);
id.setText(idi);
String a = rs.getString("Name");
name.setText(a);
String b = rs.getString("Contact");
contact.setText(b);
String c = rs.getString("Email");
email.setText(c);
String d = rs.getString("Residence");
residence.setText(d);
String e = rs.getString("Job_Type");
comboJob.setSelectedItem(e);
}
else {
rs.previous();
}
}
catch(SQLException | HeadlessException ex)
{
JOptionPane.showMessageDialog(null, ex);
}finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
you need to store the values from database in an array and then iterate over it with your (prev,next) button like
i=0;
while(rs.next()) {
dataset["ID"][i]=Integer.toString(rs.getInt("ID"));
dataset["Name"][i]=rs.getString("EName");
i++
}
to display information you can use dataset array like
id.setText(dataset["ID"][i]);
name.setText(dataset["EName"][i]);
not checked syntax but the logic is correct.
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 working with Oracle Database 10g, java and try to use ResultSet to insert new row.
I have object of ResultSet which is updateble and insensitive in direction meaning that you can traverse in any direction.
When I insert row in ResultSet using moveToInsertRow, insertRow, and setter method, the row is inserted in Database, but while traversing ResultSet, I am not able to view newly inserted row
Can any one help me.
My Code is :
import java.sql.*;
import java.io.*;
import java.util.Date;
public class TestResultSet{
public static void main(String...args){
try{
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#//localhost:1521/xe", "system", "admin");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("Select EnrNo, Name, Gender, DOB From Student");
int i;
while(rs.next()){
for(i = 1; i < 5; i++)
System.out.print(rs.getString(i) + ", ");
System.out.println();
}
//Inserting New Row
rs.moveToInsertRow();
rs.updateLong(1, 117020365276L);
rs.updateString(2, "Ashfaq");
rs.updateInt(3, 1);
Date d = new Date();
rs.updateDate(4, new java.sql.Date(d.getYear(), d.getMonth(), d.getDay()));
rs.insertRow();
//New Row Insertion ends here
rs.first(); //Moving to first row
do{
for(i = 1; i < 5; i++) //Index starts from 1, not from 0
System.out.print(rs.getString(i) + ", ");
System.out.println();
}while(rs.next());
}
catch(SQLException ex){ ex.printStackTrace(); }
catch(Exception ex){ ex.printStackTrace(); }
}
}
/*
Student Table Schema
EnrNo Numeric(12) Primary Key
Name varchar2(25);
Gender Numeric(1);
DOB date
*/
The problem is that the new row has been added to the database, not to the current rows recovered from database. So, in order to recognize the new row, you must do another read to your table(s). It could be inneficient (since it depends on how many rows and how complex your query is) but that's how it works.
Knowing this, your code should be like this:
ResultSet rs = stmt.executeQuery("Select EnrNo, Name, Gender, DOB From Student");
int i;
while(rs.next()) {
for(i = 1; i < 5; i++)
System.out.print(rs.getString(i) + ", ");
System.out.println();
}
//Inserting New Row
rs.moveToInsertRow();
rs.updateLong(1, 117020365276L);
rs.updateString(2, "Ashfaq");
rs.updateInt(3, 1);
Date d = new Date();
rs.updateDate(4, new java.sql.Date(d.getYear(), d.getMonth(), d.getDay()));
rs.insertRow();
//New Row Insertion ends here
//Moving to first row of the current recovered resultset
//thus not working as expected
//rs.first();
//close the resultset
rs.close();
//retrieve the rows from database again
rs = stmt.executeQuery("Select EnrNo, Name, Gender, DOB From Student");
do{
for(i = 1; i < 5; i++) //Index starts from 1, not from 0
System.out.print(rs.getString(i) + ", ");
System.out.println();
} while(rs.next());
I remember there were third party libraries that supported the functionality you are looking for, they are pretty expensive.
In general, yes, you will have to refetch. However, you can be smart about it: you can intelligently partition your query to fetch only a few hundred rows
e.g. by using two tables, one for production data, other for new
data, and sometimes merging them (you can use in-memory tables for the new data, and you can create cross-table views, if needed, although not neccessary)
you can create an autoincrement index, and fetch only the latest rows,
or you can use ROWNUM in Oracle, SELECT TOP in SQL Server, LIMIT in MySQL, etc.
and of course, you can implement a custom database driver :-)
In general, if you fetch more than a few hundred rows regularly, something is wrong, and maybe you should reconsider your client side interface and implementation.
A ResultSet that is TYPE_SCROLL_INSENSITIVE is not meant to detect updates to the underlying database (that is what the insensitive means here). If you want the ResultSet to detect changes, then you should use TYPE_SCROLL_SENSITIVE.
However as the changes usually occur in a different transaction, I believe most databases are unable to offer TYPE_SCROLL_SENSITIVE, and if they can then they probably only allow you to see changes to the data of the selected rows, but not detect additional (or removed) rows.
If you try to use TYPE_SCROLL_SENSITIVE, you might want to check if your database actually supports that type (eg using DatabaseMetaData.supportsResultSetType(int)). Or by checking if the created ResultSet is actually of the specified type (the JDBC spec allows drivers to 'downgrade' type and/or concurrency if it isn't supported).
You might also want to check DatabaseMetaData.ownInsertsAreVisible(int) and related methods for your specific database and driver.
Try this:
String query = "Select EnrNo, Name, Gender, DOB From Student";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// change this to reflect your specific situation
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String EnrNo = rs.getString("EnrNo");
String name = rs.getString("Name");
String gender = rs.getString("Gender");
String date = rs.getString("DOB");
System.out.println(EnrNo + "\t" + name + "\t" + gender + "\t" + date);
}
} catch (SQLException e) {
e.printStackTrace();
}
// make sure you add these as your class variables:
Connection conn = null;
Statement stmt = null;