unable to get data from the database in a JTable? - java

i'm trying to display the data of a table in the form of a JTable.
My table is in Oracle 10g Express Edition.
T.name: Doctor
I want that the entire table should be displayed in my form with the help of a JTable.
class PatientTableFromDatabase extends JFrame
{
static Connection con=null;
Statement st=null;
ResultSet rs=null;
PatientTableFromDatabase()
{
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
// Connect to the Database
try{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//cn=DriverManager.getConnection("Jdbc:Odbc:pat");
Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1522:xe", "hr", "hr");
}
catch(Exception e)
{
//System.out.println(e);
e.printStackTrace();
}
// Read data from a table
String sql = "Select * from Doctor";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement(md.getColumnName(i));
}
// Get row data
while (rs.next())
{
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement(rs.getObject(i));
}
data.addElement( row );
}
}
catch(Exception e)
{
System.out.println( e );
//e.printStackTrace();
}
// Create table with database data
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add( scrollPane );
/* JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );*/
}
public static void main(String[] args)
{
PatientTableFromDatabase frame = new PatientTableFromDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
when i run the frame appears but with no data,no table.
Please Help!!
Thanks

you sql query is empty
ResultSet rs = stmt.executeQuery( );
try with
ResultSet rs = stmt.executeQuery( sql);

You have two variables called con
The first one is the static one defined at the top of your class, and then you define it again in your try-catch block on line 21.
On line 34 you are using the uninitialized version of con and therefore you get the NullPointerException.
To fix this issue change the code to the following:
...
try{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//cn=DriverManager.getConnection("Jdbc:Odbc:pat");
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1522:xe", "hr", "hr");
}
catch(Exception e) {
e.printStackTrace();
}
...

Related

Why does i get only the last row from the database?

I use Netbeans 8.2. I'm trying to get data from the database and display it in a jTable.
But, when I run the program, I get the last row only.
Can anyone help me solve it?
public class MultiSpanCellTableExample extends JFrame {
Statement st;
ResultSet rs;
Object [][]row;
Object[] column;
MultiSpanCellTableExample() {
column = new Object[]{"","","","",""};
String g="",h="",j="",z="",n="",hg="",oo="",zz="";
Double l=null;
Date i=null;
String sql="SELECT * from personn";
con=Connections.getConnection();
try{
st=con.createStatement();
rs=st.executeQuery(sql);
while(rs.next()){
g=rs.getString("NAMME");
l=rs.getDouble("TOTAL");
i=rs.getDate("DATEE");
z=rs.getString("WY");
n=rs.getString("BAA");
row=new Object[][]{{g,l,z,i,n}};
}
}
catch(Exception e){
System.out.print( e);
}
AttributiveCellTableModel ml = new AttributiveCellTableModel(row,column);
final CellSpan cellAtt =(CellSpan)ml.getCellAttribute();
final MultiSpanCellTable table = new MultiSpanCellTable(ml);
JScrollPane scroll = new JScrollPane( table );
Box box = new Box(BoxLayout.X_AXIS);
box.add(scroll);
box.add(new JSeparator(SwingConstants.HORIZONTAL));
box.add(p_buttons);
getContentPane().add( box );
setSize( 400, 200 );
setVisible(true);
}
public static void main(String[] args) {
MultiSpanCellTableExample frame = new MultiSpanCellTableExample();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit(0);
}
});
}
}
Problem
You have not initialized row[][] with the required number of rows. Moreover, you are not storing the records into row[i], where i is the index. Note that a 2-D array is an array of arrays and therefore each record from the database represent a 1-D array which needs to be stored into row[i].
Solution
try{
// Get the number of rows
Statment stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rsCount = stmt.executeQuery("SELECT count(*) from personn");
if(rsCount.next()) {
// Initialize row[][]
row = new Object[rsCount.getInt(1)][];
st = con.createStatement();
rs = st.executeQuery(sql);
for(int i = 0; rs.next(); i++) {
g = rs.getString("NAMME");
l = rs.getDouble("TOTAL");
i = rs.getDate("DATEE");
z = rs.getString("WY");
n = rs.getString("BAA");
// Store the record into row[i]
row[i] = new Object[]{g,l,z,i,n};
}
}
}

jTable only displays first record from model

I have migrated from C# to java, so I'm a novice in java technologies.
I'm trying to populate data from SQLSERVER to jTable, using DefaultTableModel. Code is here.
public class mainScreen extends javax.swing.JFrame {
public mainScreen() {
initComponents();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=Northwind;user=im;password=123;";
Connection con = DriverManager.getConnection(connectionUrl);
Statement stmt = null;
ResultSet rs = null;
// SQL query command
String SQL = "SELECT * FROM Products";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
ResultSetMetaData mtd=rs.getMetaData();
int columns=mtd.getColumnCount();
Vector columnName=new Vector();
Vector DataRows=new Vector();
DefaultTableModel dtm=new DefaultTableModel();
for(int i=1; i<columns; i++)
{
columnName.addElement(mtd.getColumnName(i));
}
dtm.setColumnIdentifiers(columnName);
while (rs.next()) {
for(int j=1; j<columns; j++){
DataRows.addElement(rs.getString(j));
//System.out.println(rs.getString(j));
}
}
Enumeration e= DataRows.elements();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
dtm.addRow(DataRows);
myTable.setModel(dtm);
dtm.fireTableDataChanged();
} catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
} catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
The problem is that this only displays the first row. Anyone can guide me regarding that?
There are multiple bugs in your code
check your while loop
while(rs.next())
if it is ending at the right point
you keep adding elements to the same DataRow. That is not creating a new row for your table.

How to display column name and set scrollbar to jtable?

connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
table_1.setModel(buildTableModel(result));
method:
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
result:
You need to wrap your JTable inside a JScrollPane, and add the resulting JScrollPane to your layout.
The sample code you provided does not show how you're adding the JTable to the JPanel or JFrame of your application.
Found a solution:
I put a JScrollPane in jframe then use following code:
connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
JTable t=new JTable();
t.setModel(buildTableModel(result));
s1.setViewportView(t);
s1 is JScrollPane.
Output:

DefaultTableModel in a JFrame only creating on Row - JAVA

Im trying to get a number of rows from a database to populate a JTable in a JFrame but its only getting the first row/entry (row 1 always). Its a list of houses + details stored in a table
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = (ResultSetMetaData) rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount-1; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
How do I print out at all the rows in the table rather than just the first?
public void displaySaleProperties() throws SQLException{
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected to database.");
// The Connection is obtained
Statement Stmt = (Statement) conn.createStatement();
// Stmt.execute(createPropertyTable);
ResultSet rs = Stmt.executeQuery("select * from PropertySale");
// It creates and displays the table
JTable table = new JTable(buildTableModel(rs));
table.setPreferredSize(new Dimension(1150,17));
// JOptionPane.showMessageDialog(null, new JScrollPane(table));
final JPanel panelOne = new JPanel();
panelOne.setVisible(true);
panelOne.setBackground(Color.LIGHT_GRAY);
// JFRAME
final JFrame topFrame = new JFrame();
topFrame.setSize(1200, 300);
topFrame.setLocationRelativeTo ( null );
topFrame.setVisible(true);
topFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// PUT TOGETHER
topFrame.add(panelOne);
panelOne.add(table);
panelOne.revalidate();
panelOne.repaint();
// Closes the Connection
} catch (SQLException e) {
System.err.println("Cannot connect to database." + e);
} finally {
if(conn != null){
conn.close();
}
}
}
Remove the line with:
table.setPreferredSize(new Dimension(1150,17));
In another way, may you want to use a scroll pane:
JTable table = new JTable(buildTableModel(rs));
JScrollPane scrollPane = new JScrollPane(table);
topFrame.add(scrollPane);

Unable to display header for jTable

These are my codes for my jTable in java swing.
private JTable getJTable() {
if (jTable == null) {
Vector columnNames = new Vector(); //Vector class allows dynamic array of objects
Vector data = new Vector();
JPanel panel = new JPanel();
panel.setSize(new Dimension(198, 106));
try {
DBController db = new DBController();
db.setUp("IT Innovation Project");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dsn = "IT Innovation Project";
String s = "jdbc:odbc:" + dsn;
Connection con = DriverManager.getConnection(s, "", "");
String sql = "Select * from forumTopics";
java.sql.Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metaData.getColumnName(i));
}
while (resultSet.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
resultSet.close();
((Connection) statement).close();
} catch (Exception e) {
System.out.println(e);
}
jTable = new JTable(data, columnNames);
TableColumn column;
for (int i = 0; i < jTable.getColumnCount(); i++) {
column = jTable.getColumnModel().getColumn(i);
column.setMaxWidth(250);
}
String header[] = {"description", "title", "category", "posted by"};
for(int i=0;i<jTable.getColumnCount();i++) {
TableColumn column1 = jTable.getTableHeader().getColumnModel().getColumn(i);
column1.setHeaderValue(header[i]);
}
jTable.setBounds(new Rectangle(82, 218, 736, 292));
jTable.setEnabled(false);
jTable.setRowHeight(50);
jTable.getRowHeight();
}
return jTable;
}
I set an array for the header of my table. However, the program only shows the data inside my database without any header. Can somebody please enlighten me? Thanks in advance.
Put your JTable in JScrollPane like
add(new JScrollPane( getJTable() ) );

Categories

Resources