I have a button called ‘View Records’. The idea is that when I click it, it displays all the records from the database in a table.
I am able to retrieve the records from the database and display them using System.out.println or JOptionPane.showMessageDialog functions however when trying to display it using a Jtable, I cannot seem to figure out what I am doing wrong.
I am new to Java and trying to teach some to myself, but I’ve been stuck at this for some time. Help would be much appreciated.
import net.proteanit.sql.DbUtils;
JTable employee_table;
class home extends JFrame implements ActionListener
public void actionPerformed(ActionEvent click)
if(click.getSource()==view_records)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connect=DriverManager.getConnection("jdbc:mysql://privatedb/employee","sava","123456");
Statement stmt=connnect.createStatement();
ResultSet rsemp = stmt.executeQuery("SELECT * FROM employee");
employee_table.setModel(DbUtils.resultSetToTableModel(rsemp));
}
catch(Exception e){
System.out.println(e.getMessage());
} finally {
This is not a Swing problem but a Java problem -- you can't work with variables if they are null. You first need to assign objects to them.
So if you get a NullPointerException, look at that line and then check to see which variable you're trying to use on that line and fix it.
Here you need to create a new JTable and assign it to the JTable variable.
Keep studying and keep reading. Consider studying basic Java first, and then moving to Swing later.
In the future, if you have similar problems, post your error messages with your question, show which line in your code is causing the error (the error/exception message will tell you).
first of all u have to download a library file rs2xml.jar(easily available).
put/include it into ur application library
import the library file by
import net.proteanit.sql.DbUtils;
connect to the database by
private void connecting() {
try
{
JavaDBConnectivity dbobj=new JavaDBConnectivity();
conn=dbobj.Connect();
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e );
}
}
// i hope u have a created a class for connecting to database(JavaDBConnectivity here)
u can create a button then add an event on mouseclick(use netbeans to do it easily)
private void submit_queryMouseClicked(java.awt.event.MouseEvent evt) {
try{
connecting();
// String query ="select * from "database name""; //use this or if u have text area for entering use the below statement
String query=QueryArea.getText();
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
s.append (QueryArea.getText()).append("\n");
jTable.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e );
}
}
after getting the ResultSet rsemp, use the following code
DefaultTableModel dtm=(DefaultTableModel) employee_table.getModel();
while(rsemp.next()){
Vector v1=new Vector();
//in the below manner do this for all the columns in ur table
v1.add(rsemp.getString("column1Name"));
v1.add(rsemp.getString("column2Name"));
//after adding like that
dtm.addRow(v1);
}
Related
I'm trying to populate my combo box with incremental ID's from my ms access database, when I run my program the program runs fine although there is no data inside the combo box and no error given from the console. Can anyone have a look through my code to see how I'm going wrong?
private JComboBox comboBox;
Connection con;
PreparedStatement pst;
ResultSet vResults;
Statement vStatement;
void updatecombo() throws SQLException {
try {
con = connectionz.getConnection();
vStatement = con.createStatement();
String vQuery = "SELECT Book_ID FROM books";
vResults = vStatement.executeQuery(vQuery);
while(vResults.next()) {
comboBox.addItem(vResults.getString("Book_ID"));
}
} catch (Exception e) {
}
}
Database
empty list
If "Book_ID" is really a string and not a numeric, problem might be with connection. If no errors exist, it might be connected to duplicate server with no data in it.
vResults.get**String**("Book_ID")
The issue was, I wasn't initialising the combo box correctly. Thanks for the comments I was completely overlooking that I wasn't printing the exception and getting to caught up in the SQL.
Good afternoon
I'm working on a project in witch I have to calculate the performance of a pump for certain parameters like rotation, number of stages, diameter and viscosity. At first I created a database using PostgreSQL with several commercial pumps. The database contains schemas as the companies that manufacture the pumps, in each schema there are tables representing the different series of pumps and the tables have several pumps organized as lines. The lines contains coefficients that represent the pumps and that are necessary to calculate the performance.
I tried to code the application in C++, but was too hard to connect with Postgre, so I ended working with Java and Netbeans (I think it's easier to newcomers). The application is running quite good so far, but I have found two problems that I cannot solve.
To select the pump to make the calculations I had to use two Jcomboboxes and a Jlist. The first Jcombobox is for selecting the manufacturer, the second to select the serie. Finally, the Jlist displays all the pumps in that serie so the user can select one.
I was able to populate the first Jcombobox with the schemas of the database (thanks to you guys, actually), the second with the tables of the schema selected in the first and the Jlist with the names of the pumps.
The first problem is that I cannot clear the second Jcombobox (the series one) after changing the selected manufacturer in the first Jcombobox, it will add more itens every time that I change the first Jcombobox, even if I re-select an item that was already selected. I tried using the command "removeAllItems()", but then it displays just one table and stop filling the Jcombobox.
The second problem is that, when I select a serie in the second Jcombobox, it doesn't immediately display the pumps in the Jlist, the Jlist starts displaing after I select another serie. So, I have to select one and then change to another so the pumps start appearing in the Jlist.
I'm sorry for the long text and the english errors, I hope its enough for you guys to understand. I know the code is not pretty, that's because I'm not so good at this yet and I'm in a bit of a hurry to deliver it.
Here is the code, without all the generated code that Netbeans does.
public final class LabPump extends javax.swing.JFrame {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
public LabPump() {
initComponents();
con = ConnectPump.connect();
FillSelectFabricante();
}
public void FillSelectFabricante(){
try {
rs = con.getMetaData().getSchemas();
while(rs.next()){
String schemas = rs.getString("TABLE_SCHEM");
if(schemas.equals("information_schema") || schemas.equals("pg_catalog")){
}
else{
selectFabricante.addItem(schemas);
}
}
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
public void FillSelectSerie(String fabricante){
//selectSerie.removeAllItems();
try {
String[] sql = {"TABLE"};
rs = con.getMetaData().getTables(null, fabricante, "%", sql);
while(rs.next()){
String tables = rs.getString(3);
selectSerie.addItem(tables);
}
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
public void FillListBomba(String fabricante, String serie){
DefaultListModel dlm = new DefaultListModel();
dlm.removeAllElements();
try{
String sql = "select * from " + fabricante + "." + serie;
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
String bomba = rs.getString("bomba");
dlm.addElement(bomba);
}
listBomba.setModel(dlm);
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
private void selectSerieActionPerformed(java.awt.event.ActionEvent evt) {
selectSerie.addActionListener((ActionEvent e) -> {
String fabricante = selectFabricante.getSelectedItem().toString();
String serie = selectSerie.getSelectedItem().toString();
FillListBomba(fabricante, serie);
});
}
private void selectFabricanteActionPerformed(java.awt.event.ActionEvent evt) {
String fabricante = selectFabricante.getSelectedItem().toString();
FillSelectSerie(fabricante);
}
Thank you all.
I managed to solve the problem just now. When the selectSerie.removeAllItems() line was uncommented the program returned a NullPointerException error.
To solve the problem I used the DefaultComboBoxModel class and then used the RemoveAllElements() method. I'm not quite sure why the other method didn't work though.
Thanks for your time and help Peter.
public void FillSelectSerie(String fabricante) {
DefaultComboBoxModel box;
box = new DefaultComboBoxModel();
box.removeAllElements();
try {
String[] sql = {"TABLE"};
rs = con.getMetaData().getTables(null, fabricante, "%", sql);
box.addElement("-");
while (rs.next()) {
String tables = rs.getString(3);
box.addElement(tables);
}
selectSerie.setModel(box);
} catch (SQLException error) {
//JOptionPane.showMessageDialog (null,error);
}
}
I am trying and failing to send data from my java gui to my MS SQL database, I have dabbled with Java in the past but by no means am I an expert, I have been sourcing help from online and I have managed to connect my database to my application but i seem to be struggling with transferring data from the text fields to the database. (I am also new to stack so please put me straight in my place if I am out of line)
I have a class for my UI and a class for the database connection, the code is from a online resource and it seems straight forward and logical to follow (in my eyes) but I cannot seem to crack what should be a simple problem. The process is get the text from the text field and insert using a statement in to the SQL database, I can send data from within my code easily but I would ideally like it from the text fields.
The code cannot seem to see the "Connection" - error = java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: class Connection
I apologise in advance if this is a very simple mistake but it is driving me insane as it should be a fairly straight forward process. In plain terms it should be able to fill out the four text fields which fill the four columns in my DB when the submit button is pressed. Any help would be greatly appreciated.
this is the code for the action on my button:
private void SubmitBTNActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String number = Number.getText();
String title = Title.getText();
String year = Year.getText();
String query = "insert into students values ('"+Name+"','"+Number+"','"+Title+"','"Year+"')";
System.out.println(query);
try {
Connection c = DatabaseConnection.getConnection();
Statement stmt = c.createStatement();
stmt.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
}
this is the code in my database class
public class DatabaseConnection {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=*******;user=****;password=******;");
}
return connection;
}
}
Thanks
I have a table with 7 columns and I'm trying to connect my database with it so as to receive data from the database and show it in the table. The code works fine when you press the button the first time but when you press it a second time, the table becomes blank and i get this error:
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
I have given my code below for the ActionPerformed method of the button.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name","root","admin123");
String query="SELECT * FROM tablename;";
Statement st = con.createStatement();
ResultSet rs= st.executeQuery(query);
DefaultTableModel tmodel = (DefaultTableModel) jTable1.getModel();
int rows=tmodel.getRowCount();
while(rows>0)
{
tmodel.removeRow(0);
}
jTable1.setModel(tmodel);
while(rs.next())
{
tmodel.addRow(new Object[] {rs.getInt("column1"),rs.getString("Column2"),rs.getString("Column3"),rs.getInt("Column4"),rs.getString("Column5"),rs.getString("Column6"),rs.getString("Column7")});
jTable1.setModel(tmodel);
}
}
catch(Exception ex)
{
System.out.println("Eception: "+ex);
}
Any help would be greatly appreciated.
your problem is with this part although it is a relatively simple fix:
int rows=tmodel.getRowCount();
while(rows>0)
{
tmodel.removeRow(0);
}
jTable1.setModel(tmodel);
what you want to do is:
while(tmodel.getRowCount()>0)
{
tmodel.removeRow(0);
}
jTable1.setModel(tmodel);
because you are setting a variable to a constant value returned by the method which means it wont be updated as you continue to delete rows
Since you never update rows inside the loop, the while will keep going forever or until an Exception is reached...
while(rows>0)
{
tmodel.removeRow(0);
}
And of course, setRowsCount() will be way simpler and less error prone.
BTW: Helping you would be easier if you pointed which line was the one throwing the exception.
I have been trying to populate a dropdown list with information that exsists in my database but have failed miserably.
I have seen multiple guides and there have been some successful codes which i have not been able to copy since i am a novice and have likely missed some step.
This is what i am currently trying:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class populategui extends JFrame
{
private JComboBox box;
private JLabel picture;
private static String[ ] filename = {rs.next};
{
try
{
Class.forName(com.microsoft.jdbc.sqlserver);
Connection con = (Connection)DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=LIVE;integratedsecurity=true");
Statement st = con.createStatement();
String query="SELECT TOP(10)*FROM ERIT";
ResultSet rs = st.executeQuery(query);
while(rs.next());
}
catch(Exception e)
{
}
};
public populategui(){
super ("the title");
setLayout(new FlowLayout());
box=new JComboBox(filename);
}
}
If u need more information please let me know.
Part of your problem is that you are "squashing" the exceptions that might tell you what the problem. Change it to this (at least):
try {
...
} catch (Exception ex) {
ex.printStackTrace();
}
so that you can see what exception is being thrown...
Better still, log the exception.
As a general rule, it is a bad idea to catch java.lang.Exception, because you could end up catching all sorts of exceptions that you haven't anticipated. And it is a TERRIBLE idea catch exceptions and just continue as if nothing had gone wrong. It makes it difficult to figure out why your program doesn't work if you throw away the key evidence.
Finally, it seems like you are trying write Java code by copy-and-pasting examples you've found on the internet. This is a recipe for writing unreliable code. You need to learn the language properly, Go buy and read a good textbook on Java programming, or take the (free) Oracle Java Tutorial.
I think you main-problem ist to no-op in you loop:
ResultSet rs = st.executeQuery(query);
while(rs.next());
That code is expandet:
ResultSet rs = st.executeQuery(query);
while(rs.next()){
// nothing to to (n-times)
}