Can't display more than one search result in jtable - java

I've been trying to get my search results to appear in a jtable. Now I've been able to display results for codes in the database which have only one variant. But some of the codes in the database have more than one variant. For instance 034\OT\01 or 034\CT\01 or 034\OT\04. Now if you put in the search 034 the jtable doesn't display anything. It does display a code in the database and all the details if there's only one line for instance 400.
I've added my search code below. Hope you can help :).
try {
String sql = "SELECT * FROM nameOfDatabase WHERE code LIKE ?";
pst=conn.prepareStatement(sql);
pst.setString(1, txt_search.getText());
rs=pst.executeQuery();
table_details.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}

Related

dynamically populating a combobox with database data issue

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.

Problem populating a Jlist based on two Jcomboboxes connected to a PostgreSQL database

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

Increasing an ID_Column value by 1 with mysql

I wrote this code which increases a jlabel content by 1.
this works perfectly with SQLite database. but when I switched to MySQL, the same syntax produces no value at all. please what seems to be the problem. the code is as follows:
try{
String sql = "Select max(ID) from ad_form";
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
String one =rs.getString("max(ID)");
id.setText(one);
int all = Integer.valueOf(id.getText());
all=all+1;
id.setText(String.valueOf(all));
}catch(SQLException | NumberFormatException e ){
JOptionPane.showMessageDialog(null,e);
}
finally{
try{
rs.close();
pst.close();
}
catch(Exception ep){
ep.getMessage();
}
}
anytime the code runs, the jlabel which is to display the value is blank.
The issue is the naming of the unnamed expression. This is going to vary by database. So simply do:
Select max(ID) as max_id from ad_form
and then:
String one =rs.getString("max_id");
This will work in any database.
I am concerned about fetching the maximum id. If your desire is to increment it by one and use it for a subsequent insert, then this is the wrong approach. Instead, you should be using an auto_increment column.

Not able to display results in a table using JTable

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

JTable Oracle Timestamp column not displayed

I have created a 'Jtable' named Department_Table and now using SQL query i am trying to populate my Database table contents to my Jtable.
I have done it successfully but the timestamp column from my Database table is not been correctly displayed.
Can you please help me to find whats wrong with this program.
Code:
public void UpdateTable()
{
try
{
Connection conn=Address.getOracleConnection();
String sql="Select * from department";
/*
Using to_char my statement looks like this and it works
String sql="Select department_id,name,to_char(created_on,'dd/MM/yyyy HH24:MI:SS') from department";
*/
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet res=pst.executeQuery();
Department_Tabel.setModel(DbUtils.resultSetToTableModel(res));
}
catch(Exception e)
{
Notify.showMessageDialog(null,""+e+"","Error Generating Table",Notify.ERROR_MESSAGE);
}
}
Output:
departmentid name createdon
1 name1 oracle.sql.TIMESTAMP#19eda2c
2 name2 oracle.sql.TIMESTAMP#59a34
This link should help you understand the mapping and do the formatting in order to display the contents properly.
http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html

Categories

Resources