How display in JTable the data from MySQL - java

I want to display the data from MySQL in JTable but showed the last row from the table and more nothing. Help me, please. I understand that I have a problem because jt = new JTable(data, columns) each time create a new table for each row (deleting previous) but I can't find the right option.
public class Test2 extends JPanel {
static final String USERNAME = "root";
static final String PASSWORD = "root";
static final String CONN_STRING = "jdbc:mysql://localhost:3306/mydbtest?useSSL=false";
JTable jt;
public Test2 () {
try {
Connection conn;
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
Statement stmt = (Statement) conn.createStatement();
String query = "Select title, season, episode from movie";
ResultSet rs = stmt.executeQuery(query);
rs.beforeFirst();
while (rs.next()) {
String title = rs.getString("Title");
String season = rs.getString("Season");
String episode = rs.getString("Episode");
String[] columns = {"Title", "S", "E"};
String[][] data = {{title, season, episode}};
jt = new JTable(data, columns);
};
jt.setPreferredScrollableViewportSize(new Dimension(450, 63));
jt.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane(jt);
add(jps);
}
catch (Exception er) {System.err.println(er);}
}
public static void main(String[] args) {
JFrame jf = new JFrame();
Test2 t = new Test2();
jf.setTitle("Test");
jf.setSize(500,500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}

Your problem is here:
while (rs.next()) {
String title = rs.getString("Title");
String season = rs.getString("Season");
String episode = rs.getString("Episode");
String[] columns = { "Title", "S", "E" };
String[][] data = { { title, season, episode } };
jt = new JTable(data, columns); // *** you're making many JTables here!! ***
}
Each time the while loop loops, you create and discard a new JTable object. The exception is on the last time through the loop, the data from the last row of the result set is not discarded and is then displayed in final JTable created. To solve this, to display all of the data within the JTable, you need to collate all of your result set data within the while loop, and then add it to the JTable, and the easiest way to do this is to create a table model, here a simple DefaultTableModel, before the while loop, and populate it within each row of result set data within the while loop:
// create a table model with the appropriate column headers
// and with 0 rows (to start with)
String[] columnNames = {"Title", "Season", "Episode"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
while (rs.next()) {
String title = rs.getString("Title");
String season = rs.getString("Season");
String episode = rs.getString("Episode");
// create a single array of one row's worth of data
String[] data = { title, season, episode } ;
// and add this row of data into the table model
tableModel.addRow(data);
}
jt.setModel(tableModel); // place model into JTable
Or perhaps better, change the last line to:
jt = new JTable(tableModel); // to create a new JTable

Try This... You Can Do it easily....
public final void EmployeeGridView(){
try{
Connection conn = DBConn.connect();
PreparedStatement ps = conn.prepareStatement("Select * from empdetails");
ResultSet rs=ps.executeQuery();
DefaultTableModel tm = (DefaultTableModel)jTable1.getModel();
tm.setRowCount(0);
while(rs.next()){
Object o[] = {rs.getInt("EMPID"),rs.getString("FirstName"),rs.getString("LastName"),rs.getString("Designation"),rs.getString("NIC"),rs.getString("PhoneNO"),rs.getString("DOB"),rs.getString("Address"),rs.getString("Gender")};
tm.addRow(o);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Error in Employee Grid View..... "+e);
}
}

Related

How can I make import the results of an sql query into a JTable?

I am trying to import the results from an SQL query into a JTable, but when I run it, it tells me that the ResultSet object has no set row?
What does this mean?
how Can I fix this?
here is what I've tried:
import javax.swing.*;
import java.sql.*;
public class GUI {
// frame
JFrame f;
// Table
JTable j;
// Constructor
GUI()
{
ResultSet result;
// Frame initiallization
f = new JFrame();
// Frame Title
f.setTitle("SQL to JTable");
try{
String dbURL = "jdbc:sqlserver://DESKTOP-TSKUNOE\\MSSQLSERVER:1433;databaseName=LMD";
String user = "programer151";
String password = "abhinav#123";
Connection connection = DriverManager.getConnection(dbURL, user, password);
String code = "select * from dbo.LMD_Table where [DATE] = '2019-02-01'";
Statement statement = connection.createStatement();
result = statement.executeQuery(code);
// Data to be displayed in the JTable
double[] data =
{result.getFloat(2), result.getFloat(3), result.getFloat(4), result.getFloat(5), result.getFloat(6), result.getFloat(7), result.getFloat(8), result.getFloat(9), result.getFloat(10), result.getFloat(11), result.getFloat(12), result.getFloat(13)};
;
String[][] data1 = new String[13][0];
for (int i = 0; i<=13; i++) {
data1[i][0] = String.valueOf(data[i]);
}
String[] columnNames = { "data", "data","data", "data", "data","data", "data", "data","data", "data", "data","data" };
j = new JTable(data1,columnNames);
j.setBounds(30, 40, 200, 300);
// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
}catch (SQLException e){
e.printStackTrace();
}
}
// Driver method
public static void main(String[] args)
{
new GUI();
}
}
the output I want is a JTable which gives me the results of an sql query
the ResultSet object has no set row?
result = statement.executeQuery(code);
double[] data = {result.getFloat(2), result.getFloat(3), ...};
You can't just access a row in the ResultSet directly. You first need to point to a row in the Result set.
This is done by invoking the next() method of the ResultSet.
Then typically you would use looping code to read each row of data in the ResultSet:
result = statement.executeQuery(code);
while (result.next())
{
// get the data from the current row of the ResultSet
}
See: How to get a DefaultTableModel object's data into a subclass of DefaultTableModel for a more complete example of how to create your DefaultTableModel from a ResultSet.
Also, you should use a PreparedStatement to build the SQL query. It will allow you to more easily set the parameters of the query. Search the forum for more information and example code.
a null pointer exception is usually something that isn't getting initialized with a value and getting a null instead. Try adding breakpoints to check where that null is and once found add:
if (variable != null) { //variable could be an object
//some code
}

How to make the table size same as the row size in java?

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);
}
}

How to add multiple rows to JTable?

I'm trying to populate a JTable from a database, but the output is still empty. Here is my code :
private void buttonsearchActionPerformed(java.awt.event.ActionEvent evt)
{
conn = DatabaseConnection.dbConnection();
try {
String Sql="select idp,nomp,prix,stock from produit where codep='"
+ textsearch.getText() + "'";
pst = conn.prepareStatement(Sql);
ResultSet rs = pst.executeQuery();
DefaultTableModel model = new DefaultTableModel();
Object[] columns = {"Id Produit", "Nom Produit", "Quantité", "Prix", "Stock"};
model.setColumnIdentifiers(columns);
table.setModel(model);
Object[] row = new Object[5];
if (rs.next())
{
row[0] = rs.getInt("idp");
row[1] = rs.getString("nomp");
//row[2] = rs.getString("");
row[3] = rs.getString("prix");
row[4] = rs.getString("stock");
model.addRow(row);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
table "poduit" is :
| idp | codep | nomp | prix | stock |
"Quantité" in
Object[] columns = {"Id Produit", "Nom Produit", "Quantité", "Prix", "Stock"};
It meant to modify numbers of items to create a billing.
my issue is the 2nd row is pasted right on the 1st one
Thanks for help
According How to add row in JTable? and the Internet itself, all examples uses following line:
DefaultTableModel deFaultTableModel = (DefaultTableModel) myJTable.getModel();
so you have to replace the code line 'DefaultTableModel model = new DefaultTableModel();' by DefaultTableModel model = (DefaultTableModel) table.getModel();.

Java UI - doesn't create and populate table

I am trying to pull data from a table in a mysql database and populate the results in a JTable. There are currently 3 tabs in the UI, the first two being input screens, which work fine. The 3rd tab, I am trying to run a query (after button is pushed) and display the results in a JTable. I am getting no error messages, but the screen does not display the table. Below is my code. Any assistance would be greatly appreciated. Note, user name and password have been replaced with generic. The query has also been simplified until I can get it to work. The system.out.print was just to check and see if it was pulling any data.
private void salePropertyActionPerformed(java.awt.event.ActionEvent evt) {
String sSelectQuery = "";
Statement statement=null;
Connection conn = null;
//PreparedStatement pStatement =null;
JPanel panel= spPanel;
TableColumn column;
JTable spTable = jTable1;
Vector columnNames = new Vector();
Vector data = new Vector();
spTable = new JTable(data,columnNames);
JScrollPane scrollPane = new JScrollPane(spTable);
panel.add(scrollPane);
try {
String myDriver = "com.mysql.jdbc.Driver";
String myURL = "jdbc:mysql://localhost:3306/realestate?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
conn=DriverManager.getConnection(myURL,"root","jul1664bd");
/*Storing SQL statement*/
sSelectQuery ="SELECT propertyID, propertyPrice FROM property";
statement = conn.createStatement();
try (ResultSet rs = statement.executeQuery(sSelectQuery) //executes the query
) {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
for(int i = 1; i<=columns; i++){
columnNames.addElement(metaData.getColumnName(i));
}
while (rs.next()){
Vector row = new Vector(columns);
for (int i=1; i<=columns; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
System.out.println(data);
}
rs.close();
for (int i=0; i<spTable.getColumnCount(); i++){
column=spTable.getColumnModel().getColumn(i);
//column.setMaxWidth(250);
}
}
statement.close();
} catch (SQLException e) {
System.err.println("An exception ocurred");
System.err.println(e.getMessage());
} catch (ClassNotFoundException ex) {
Logger.getLogger(realEstateUI.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(this,"Query Complete");
}
/**
You are attempting to add the JTable after the UI is visible. For the addition to take affect you must call revalidate followed by repaint. As an alternative, add your JTable upon UI construction (before it is visible) and populate the model of the JTable in salePropertyActionPerformed

create jtable from database using codes and displaying database table records in it

Yow, I am trying to add a jTable in my jFrame and I wanna display records from my database table to the jTable.
I was able to create a jTable(I put the code in the constructor) and manually inputted in the code the values to be displayed. It worked. But then when I try to call a method that retrieves data from the database, and try to display them inside the jtable. It gives me an error "NullPointerException".
CODE in my constructor that creates the table:
String[] columnname = {"Subject Code", "Prelim", "Midterm", "SemiFinal", "Finals"};
setTable();
Object[][] data = {};
gradetable = new JTable(data, columnname){
public boolean isCellEditable(int data, int columns){
return false;
}
public Component prepareRenderer(TableCellRenderer r, int data, int columns){
Component c = super.prepareRenderer(r, data, columns);
if (data % 2 == 0){
c.setBackground(Color.GRAY);
}
else{
c.setBackground(Color.WHITE);
}
if (isCellSelected(data, columns)){
c.setBackground(Color.ORANGE);
}
return c;
}
};
gradetable.setPreferredScrollableViewportSize(new Dimension (400, 150));
gradetable.setFillsViewportHeight(true);
jsp = new JScrollPane(gradetable);
Method I used to retrieve the data from the database and add them to the table:
private void setTable(){
DefaultTableModel model = (DefaultTableModel)gradetable.getModel();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/grading","root","");
Statement st = con.createStatement();
String sql = "SELECT * FROM student INNER JOIN grade ON student.idnumber = grade.idnumber WHERE student.idnumber = '2010-00125'";
ResultSet rs = st.executeQuery(sql);
model.setRowCount(0);
while (rs.next()){
//this.setName(rs.getString("name"));
//this.setCourse(rs.getString("course"));
//this.setYear(rs.getString("year"));
String d1, d2, d4, d3, d5;
d1 = rs.getString("subjectcode");
d2 = rs.getString("prelim");
d3 = rs.getString("midterm");
d4 = rs.getString("semifinal");
d5 = rs.getString("finals");
model.addRow(new Object[]{d1,d2,d3,d4,d5});
}
rs.close();
con.close();
}catch(ClassNotFoundException | SQLException ex){
JOptionPane.showMessageDialog(null, ex);
}
}
The reason for the NPE is that you are calling setTable which tries to get the JTable model here:
DefaultTableModel model = (DefaultTableModel)gradetable.getModel();
This is before you have actually instantiated gradetable, so the NPE is thrown.
Aside from this, you need to use DefaultTableModel when setting the model of the JTable, otherwise you will get a ClassCastException on this line.

Categories

Resources