add extra column which do not exist in the database - java

Below is my code to create a table from my database. I would like to add a checkbox column at the end which will not be in the database. it is just part of the front end. the Could you please help?
my getRow() method keep returning -1 although a row is selected, any suggestion?
package Default;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.sql.*;
/**
* This class create JTable from Database table.
* User program needs to specify database connection and corresponding a table name.
*
*/
public class DBTable{
//private String table;
DefaultTableModel dm=new DefaultTableModel();
JTable t1=new JTable();
Object row[];
String c[];
int cols;
PreparedStatement pst;
ResultSet rs ;
public DBTable(Connection conn){
conn=Login.con;
}
/**
* This method return JTable object created from Database table having selected data and structur * as in original table into database.
* #param table Name of the database table to be coverted to JTable
* #param query Select query to specify selected columns and data to extracted from database table
* #return JTable object that consist of selected data and structure of Database table
* #throws java.lang.Exception Original object is deferent, e.i either SQLException or NullPointerException
*/
public JTable getTable(String table,String query)throws Exception{
JTable t1=new JTable();
DefaultTableModel dm=new DefaultTableModel();
Statement st= Login.con.createStatement();
ResultSet rs=st.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
//Coding to get columns-
int cols=rsmd.getColumnCount();
String c[]=new String[cols];
for(int i=0;i<cols;i++){
c[i]=rsmd.getColumnName(i+1);
dm.addColumn(c[i]);
}
//get data from rows
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
t1.setModel(dm);
return t1;
}
public int getRow(){
int row = t1.getSelectedRow();
JOptionPane.showMessageDialog(null, row);
return row;
}
public void deleteRow(String sql){
try {
String value = (String) t1.getValueAt(getRow(), 0);
JOptionPane.showMessageDialog(null, value);
pst = Login.con.prepareStatement(sql);
pst.setString(1, value);
((DefaultTableModel)t1.getModel()).removeRow(getRow());
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
}
}

You are using a DefaultTableModel so after you create the model you can manually add a column:
model.addColumn("CheckBox Column");

Related

how to display the reference of FK ID in JTable (JAVA)

Hi,
I have a multiple tables in my Database and some of those tables have relationship with my employee_details table, and now, I want to display the records from the employee_details table to my JTable. But I want the FK ID string valued instead of the actual ID.
public void DBTable(){
try {
String InsertToTable = "Select EmpDetails_ID, First_Name, Last_Name, Gender, Position_ID, Department_ID, "
+ "Office_Location_ID, Employee_Status, Office_Number, Mobile_Number, Email_Address, Remarks, Image From employee_details";
pst = con.prepareStatement(InsertToTable);
rs= pst.executeQuery();
EmpDBTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
Logger.getLogger(Employee_Details.class.getName()).log(Level.SEVERE,null,ex);
}
}
I modified an example code I've found online. I downloaded rs2xml.jar to get "DbUtils.resultSetToTableModel(rs)". I created your tables employee_details and department in my local sql server. I used SQL Join example I gave you and was able to get that extra column on JTable. Please compare this example with your own code. In this code, I get the following result:
Here is the code (modified from an online example):
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.awt.event.*;
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
import net.proteanit.sql.DbUtils;
public class SearchResult {
JFrame frame, frame1;
JPanel panel;
static JTable table;
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://localhost;instance=DESKTOP-8QFTIP4;databaseName=deneme;user=sa;password=******";
String userName = "sa";
String password = "*****";
public void createUI()
{
showTableData();
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
table = new JTable();
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
try
{
Class.forName(driverName);
System.out.println("conn before");
Connection con = DriverManager.getConnection(url, userName, password);
System.out.println("conn after");
String sql ="Select EmpDetails_ID, First_Name, Last_Name, Gender, Position_ID, "
+ " employee_details.Department_ID,department.Department_Name , Office_Location_ID, Employee_Status, "
+ " Office_Number, Mobile_Number, Email_Address, Remarks, Image "
+ " From employee_details inner join department on employee_details.Department_ID = department.Department_ID";
PreparedStatement ps = con.prepareStatement(sql);
System.out.println("about to execute");
ResultSet rs = ps.executeQuery();
int i =0;
System.out.println("after to execute");
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception ex)
{
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400,300);
}
public static void main(String args[])
{
SearchResult sr = new SearchResult();
sr.createUI();
}
}

JFileChooser calls file explorer twice before item is selected [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm trying to use JFileChooser to get the directory of a database file for my inventory control software.
The problem is that JFileChooser only gets the directory of the file after the file explorer is displayed twice and the file is chosen twice.
The code is below:
package groupassignment;
import java.io.File;
import java.sql.Connection;
import java.sql.*;
import java.sql.SQLException;
import javax.swing.*;
/**
*
* #author ashraf141298
*/
public class GetDatabase {
static Connection con;
static Statement st;
static ResultSet rs;
public GetDatabase() {
connect();
}
public String getFileDirectory() {
JFileChooser filechooser = new JFileChooser();
File db = null;
String directory;
if(filechooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
db = filechooser.getSelectedFile();
System.out.println("Opening file: " + db);
} else {
System.out.println("No file was chosen or an error occured");
System.exit(0);
};
directory = db.toString();
return directory;
}
public void connect() {
try{
String dbURL = "jdbc:ucanaccess://" + getFileDirectory();
// Attempt to connect to the database
con = DriverManager.getConnection(dbURL);
// Extract data from the table using SQL sta
st = con.createStatement();
String query = "select * from ProductBarcodes";
rs = st.executeQuery(query);
} catch(SQLException e){
JOptionPane.showMessageDialog(null, "Unable to connect to database", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
public static void main(String[] args) {
GetDatabase database = new GetDatabase();
DisplayDatabase gui = new DisplayDatabase();
}
}
Code for DisplayDatabase:
package groupassignment;
import static groupassignment.GetDatabase.rs;
import javax.swing.*;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
/**
*
* #author ashraf141298
*/
public class DisplayDatabase extends GetDatabase {
public DisplayDatabase() {
display();
}
public void display() {
// It creates and displays the table
JTable table = null;
try {
table = new JTable(buildTableModel(rs));
} catch (SQLException ex) {
System.out.println("Unable to create JTable");
}
// Closes the Connection
JOptionPane.showMessageDialog(null, new JScrollPane(table), "Current Stocklist", JOptionPane.INFORMATION_MESSAGE);
}
public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// get the 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));
}
// get the 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 the database in TableModel form
return new DefaultTableModel(data, columnNames);
}
}
you have extends DisplayDatabase with GetDatabase class
DisplayDatabase extends GetDatabase{
...
}
so when you create a new instance of GetDatabase class constructor of super class [GetDatabase] get invoked and connect method get called again.
so you get another jfilechooser popup window.
GetDatabase database = new GetDatabase();
so how to fix
if you don't want to inherit anything from GetDatabase class you can remove extends part.
but if you want to inherit from GetDatabase class then,
instead of connect db from constructor , you can do it from a method.
public GetDatabase() {
// connect();// not here
}
public void ConnectDatabase(){
connect();
}
so you call this method .
public static void main(String[] args) {
GetDatabase database = new GetDatabase();
database.ConnectDatabase();
DisplayDatabase gui = new DisplayDatabase();
}
May be the function is being triggered more than once, your code for calling file chooser seems to work fine.

How to display multiple records of mysql in java

So at the moment I have a class called MySqlConnection with this code inside it
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class MySqlConnection {
public static void Connection() throws Exception {
// Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver");
// Creating a variable for the connection called "con"
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Friends", "John", "John123");
// jdbc:mysql://localhost:3306/employee_record --> This is the database
// root is the database user
// root is the password
// Here we create our query
PreparedStatement Statement = con
.prepareStatement("SELECT * FROM names ORDER BY first");
// Creating a variable to execute query
ResultSet result = Statement.executeQuery();
while (result.next()) {
System.out.println(result.getString(1) + " " + result.getString(2));
}
}
}
When I run this, it displays all the results at once in the Eclipse IDE.
http://i.imgur.com/V9kA5fN.png
How do I make it display all the results in a separate window?
You can use JTable on the JFrame to show the data in tabular format on a window. You can find examples on Internet about using JTable.
You can use JTable. Here is my version
public class JResultTable extends JTable {
public DefaultTableModel dataModel;
ResultSet rs;
public void init_model(){
dataModel=new DefaultTableModel();
}
public void add_data() throws SQLException {
String colNames[];
ResultSetMetaData rsMetaData=rs.getMetaData();
int colCount=rsMetaData.getColumnCount();
colNames=new String[colCount];
for(int i=1;i<=colCount;i++)
colNames[i-1]=rsMetaData.getColumnName(i).toUpperCase();
dataModel.setColumnIdentifiers(colNames);
while(rs.next())
{
String[] rowdata= new String[colCount];
for(int i=1;i<=colCount;i++)
rowdata[i-1]=rs.getString(i);
dataModel.addRow(rowdata);
}
}
JResultTable(ResultSet rs) throws SQLException {
super();
init_model();
this.rs=rs;
add_data();
setModel(dataModel);
}
}
Ex- JResultTable mm=new JResultTable(rs)// rs is the resultset. Column Names will automatically become table headers (ResultSetMetaData)
add this mm to a panel or frame.

Java Oracle database connection error

I am new to Java and Oracle. I am trying to make an application that lists serial numbers of a product and when you click on a product's serial number from the list, it shows the other column informations from the database in a textbox. I have a form named CRUD.I am using Oracle 10g. Code is here:
package project1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class CRUD extends javax.swing.JFrame {
Connection connection = null;
public CRUD() {
try {
initComponents();
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
String serverName = "192.168.0.36";
String portNumber = "1521";
String sid = "XE";
String url = "jdbc:oracle:thin:#"+serverName+":"+portNumber+":"+sid;
String userName = "HR";
String password = "hr";
try {
connection = DriverManager.getConnection(url,userName,password);
} catch (SQLException ex) {
Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
}
try {
String temp="";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SERI_NO FROM KART");
while(rs.next()) // dönebildiği süre boyunca
{
String s = rs.getString("SERI_NO") ; //kolon isimleri oluşturuldu
temp+=s+"_";
}
Object [] tem_obj;
tem_obj=temp.split("_");
listOgrenciler.setListData(tem_obj);
} catch (SQLException ex) {
Logger.getLogger(edit.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
}
listOgrenciler.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
if (!arg0.getValueIsAdjusting()) {
try {
Statement stmtx = connection.createStatement();
Object[] sss=listOgrenciler.getSelectedValues();
String swhere="" ;
for (int i = 0; i < sss.length; i++) {
swhere+=sss[i].toString()+",";
}
swhere=swhere.substring(0,swhere.length()-1);
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ("+swhere+")") ;
String temp="";
Object [] tem_obj;
tem_obj=temp.split("_");
String ara="";
for (int i = 0; i < tem_obj.length; i++) {
ara+=tem_obj[i].toString()+"\n";
}
texttoarea.setText(ara);
} catch (SQLException ex)
{
Logger.getLogger(edit.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
Errors i get are here:
20.Şub.2014 11:22:11 project1.CRUD$1 valueChanged
SEVERE: null
java.sql.SQLSyntaxErrorException: ORA-00904: "SNS080961097": invalid identifier
.....
at project1.CRUD$1.valueChanged(CRUD.java:78)
......
As I said before, I am new to both Java and Oracle. If the errors are so obvious don't laugh:)
Your this query
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ("+swhere+")") ;
should be like this:
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ('"+swhere+"')") ;
Actually there is no problems with you connection step to Oracle DB, its connected successfully, Your problem is within the query. make sure that you have a SERI_NO column in your KART table.
i suggest you to RUN the both same queries in you code from any SQL client such SQLDeveloper and see what these queries retrieve.
Observe this statement once,
swhere=swhere.substring(0,swhere.length()-1);
replace the above statement with the following
shere=swhere.substring(0,swhere.length()-2);
Because an extra comma(,) is included in your sql statement.
There is no issue with your connection.
Please add some logging to your code and you will know exactly where the error is throwing.
I guess the error is throwing in this line..
SELECT * FROM KART where SERI_NO in ("+swhere+")
You have to specify this as a string with '',where you actual select should look like below.
SELECT * FROM KART where SERI_NO in ('ABC','XCV');
so please check with this one check the value of the "swhere"

how to get data from mysql to jList?

I'm new in java.
how can I get the data from mysql and display it in Jlist (Jlist name: JLISTF)
I'm confused with vector and the model.
Below is the photo of my JFRAME
the yellow part means JLIST and it's name is JLISTF
I want to display the data from mysql
Thank you
code:
public class Inventory extends javax.swing.JFrame {
Connection connect = null;
ResultSet rs = null;
PreparedStatement pst = null;
ResultSet rs2 = null;
public void populateJList(JList ItemList, String query, Connection connection) throws SQLException
{
DefaultListModel model = new DefaultListModel(); //create a new list model
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query); //run your query
while (resultSet.next()) //go through each row that your query returns
{
String ItemList2 = resultSet.getString("ItemCode"); //get the element in column "item_code"
model.addElement(ItemList2); //add each item to the model
}
ItemList.setModel(model);
resultSet.close();
statement.close();
}
public Inventory() {..}
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) { ......}
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
try{.........}
catch()
{...........}
}
Assuming you have a connection to your database and you know what information you want to query, you can use the following method to populate your JList.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.DefaultListModel;
import javax.swing.JList;
...
public void populateJList(JList list, String query, Connection connection) throws SQLException
{
DefaultListModel model = new DefaultListModel(); //create a new list model
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query); //run your query
while (resultSet.next()) //go through each row that your query returns
{
String itemCode = resultSet.getString("item_code"); //get the element in column "item_code"
model.addElement(itemCode); //add each item to the model
}
list.setModel(model);
resultSet.close();
statement.close();
}
You would pass your JLISTF variable into this function as the first parameter.
The following line assumes that your column name is "item_code", you will want to replace this with your columns actual name.
String itemCode = resultSet.getString("item_code");
This function creates a new Model (see How to Use Models), then executes your query. It gets each value that your query returns and adds it to the new model. list.setModel(model) then tells the list to start using your new model.

Categories