how to display the reference of FK ID in JTable (JAVA) - 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();
}
}

Related

Creating database and tables directly from Java

I'm trying to create the tables directly form Java instead of creating them using phpMyAdmin. The code looks like that runs smooth, but when the queries arrive, it gives some kind of error that I'm trying to identify and I'm not capable. Here's the code I've been trying:
package filmoteca;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class GestionBDD {
private static String datosConexion = "jdbc:mysql://127.0.0.1:3306/";
private static String baseDatos = "cine";
private static String usuario = "root";
private static String pass = "";
private static String tabla = "pelicula";
private Connection con;
public GestionBDD() {
try {
con = DriverManager.getConnection(datosConexion, usuario, pass);
try{
crearBDD();
crearTablas();
}catch(Exception e){
e.printStackTrace();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
public void crearBDD() throws Exception{
String query = "CREATE DATABASE IF NOT EXISTS"+ baseDatos +";";
Statement stat = null;
try{
stat = con.createStatement();
stat.executeUpdate(query);
con = DriverManager.getConnection(datosConexion+baseDatos, usuario, pass);
}catch(SQLException e){
e.printStackTrace();
}finally{
stat.close();
}
}
public void crearTablas() throws Exception{
String query = "USE DATABASE "+baseDatos+";"+
"CREATE TABLE IF NOT EXISTS"+" "+tabla+"("
+ "titulo VARCHAR(30), "
+ "director VARCHAR(30), "
+ "pais VARCHAR(30), "
+ "duracion FLOAT, "
+ "genero VARCHAR(30));";
Statement stat = null;
try{
stat = con.createStatement();
stat.executeUpdate(query);
con = DriverManager.getConnection(datosConexion+baseDatos, usuario, pass);
}catch(SQLException e){
e.printStackTrace();
}finally{
stat.close();
}
}
}

Retrieve values from database to jradiobutton

I'm trying to implement a payroll system and I got some issues with the updating employees. I have stored the gender of the employees as a varchar in my DB. When I type in the employee id and click search button I want to get that info out of the database and display it in a male/female radio buttons according to the data. There are no errors in the code. but the problem is when I try to do that only male button appear selected which is by the way the default. Female radio button doesn't get selected even when the the data on the DB says Female. Can anybody please help me with this issue? below is my code.
package AppPackage;
import static AppPackage.AddEmployeeGUI.convertUtilDateToSqlDate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class UpdateEmployeeGUI extends javax.swing.JFrame {
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
public UpdateEmployeeGUI() {
initComponents();
conn=MySQLConnect.ConnectDb();
}
private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "SELECT * FROM EmployeeInfo WHERE EmployeeID =?";
pst=conn.prepareStatement(sql);
pst.setString(1,EmployeeIDSearchField.getText());
rs = pst.executeQuery();
if(rs.next()) {
String ID = rs.getString("EmployeeID");
EmployeeIDField.setText(ID);
String FN = rs.getString("FirstName");
FirstNameField.setText(FN);
String LN = rs.getString("LastName");
LastNameF.setText(LN);
String GN = rs.getString("Gender");
if (GN =="Female"){
MaleRadio.setSelected(false);
FemaleRadio.setSelected(true);
}
else{
FemaleRadio.setSelected(false);
MaleRadio.setSelected(true);
}
String CN = rs.getString("ContactNo");
ContactNoField.setText(CN);
String EM = rs.getString("Email");
EmailField.setText(EM);
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Date dateValue = null;
try {
dateValue = date.parse(rs.getString("DateOfJoin"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
jDateChooser.setDate(dateValue);
String Des = rs.getString("Designation");
DesignationComboBox.addItem(Des); //getItemAt(int index);
String BS = rs.getString("BasicSalary");
BasicSalaryField.setText(BS);
}
} catch (SQLException e ) {
JOptionPane.showMessageDialog(null, e);
}
}
private void UpdateEmployeeButtonActionPerformed(java.awt.event.ActionEvent evt) {
// UPDATE EmployeeInfo SET FirstName='?', LastName='?', LastName='?', Gender='?', ContactNo='?',Email='?', DateOfJoin='?', Designation='?' WHERE EmployeeID='?';
try{
String sql1 = "UPDATE EmployeeInfo SET FirstName=?, LastName=?, Gender=?, ContactNo=?, Email=?, DateOfJoin=?, Designation=?, BasicSalary=? WHERE EmployeeID=?";
pst=conn.prepareStatement(sql1);
pst.setString(1,FirstNameField.getText());
pst.setString(2,LastNameF.getText());
pst.setString(3,GenderC);
pst.setString(4,ContactNoField.getText());
pst.setString(5,EmailField.getText());
pst.setDate(6,convertUtilDateToSqlDate(jDateChooser.getDate()));
pst.setString(7,DesignationComboBox.getSelectedItem().toString());
pst.setString(8,BasicSalaryField.getText());
pst.setString(9,EmployeeIDField.getText());
pst.execute();
String sql2 = "UPDATE employeebasicsalary SET BasicSalary=? WHERE EmployeeID=?";
pst=conn.prepareStatement(sql2);
pst.setString(1,BasicSalaryField.getText());
pst.setString(2,EmployeeIDField.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Successfully updated!");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
private void FemaleRadioActionPerformed(java.awt.event.ActionEvent evt) {
GenderC = "Female";
}
private void MaleRadioActionPerformed(java.awt.event.ActionEvent evt) {
GenderC = "Male";
}
private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {
EmployeeIDField.setText(null);
FirstNameField.setText(null);
LastNameF.setText(null);
MaleRadio.setSelected(true);
FemaleRadio.setSelected(false);
ContactNoField.setText(null);
EmailField.setText(null);
jDateChooser.setCalendar(null);
BasicSalaryField.setText(null);
DesignationComboBox.setSelectedIndex(0);
}
replace the lines
if (GN =="Female"){
MaleRadio.setSelected(false);
FemaleRadio.setSelected(true);
}
else{
FemaleRadio.setSelected(false);
MaleRadio.setSelected(true);
}
with
if (GN.equals("Female")){
MaleRadio.setSelected(false);
FemaleRadio.setSelected(true);
} else {
FemaleRadio.setSelected(false);
MaleRadio.setSelected(true);
}
as == is used to compare the hash and values & .equals is used to check the values only..

Record not getting deleted from MySQL database's table while it's deleted from Java GUI?

Edited Question
When I click the delete button, The row in the table gets deleted in GUI but not from database in mysql server.
Here's the code:
// DatabaseStore. This part runs fine.
public class DatabaseStore {
private final String server = "jdbc:mysql://localhost/";
private final String database = "music_magic";
private final String user_name = "root";
private final String pass_word = "";
private final String driver = "com.mysql.jdbc.Driver";
public Connection doConnection() {
Connection c;
try {
//load the driver
Class.forName(driver);
c = DriverManager.getConnection(server + database, user_name, pass_word);
// JOptionPane.showMessageDialog(null, "Database connected");
} catch (Exception e) {
c = null;
JOptionPane.showMessageDialog(null, "Error : " + e.getMessage());
}
return c;
}
//
// Imports
import Database_music.DatabaseStore; //main database page where i connect to database
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import magic_music.Items; //ignore this
//...
// Subject method
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(jTable1.getSelectedRow() >=0){
try{
DatabaseStore dtbs = new DatabaseStore();
Connection cn = dtbs.doConnection();
Statement stat = cn.createStatement();
String sql = "DELETE FROM products_info WHERE Product_id ='"+jTable1.getSelectedRow() +"'";
stat.executeUpdate(sql);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.removeRow(jTable1.getSelectedRow());
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
JOptionPane.showMessageDialog(null, "sql err");
}
} else {
JOptionPane.showMessageDialog(null, "Please select an item to delete");
}
}
Please tell me what am I doing wrong?

Jtable how to display data from mysql in different Columns

I am trying to display data from the database in java using Jtable, yes I have achieved that but now the conflict is the surname and name they are displayed in one Column yet I would like them to be displayed in different columns . below is my code please help ..
import java.awt.Dimension;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.*;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ju {
private static Object request;
static JTable mysTable;
//constructor method
public static void main (String args []){
String [] columnNames = {"Name","Lastname","Id","Style"};
mysTable = new JTable(4,4);
mysTable.setBounds(20,10,300,300);
JFrame frame = new JFrame("King Musa Saloon Software");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(500,500);
frame.setResizable(false);
frame.setVisible(true);
frame.add(mysTable);
//frame.add(mysTable);
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loading success!");
String url = "jdbc:mysql://localhost:3306/saloon";
String name = "root";
String password = "";
try {
java.sql.Connection con = DriverManager.getConnection(url, name, password);
System.out.println("Connected.");
// pull data from the database
java.sql.Statement stmts = null;
String query = "select userid, username, name from saloonuser ";
stmts = con.createStatement();
ResultSet rs = stmts.executeQuery(query);
int li_row = 0;
while(rs.next()){
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,0);
int userid = rs.getInt("userid");
String username = rs.getString("username");
String name1 = rs.getString("name");
System.out.println(name1);
li_row++;
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Take a look at your code here:
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,0);
It's writing in the same column, you should change it to:
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,1);
Try and see if it work :)

SELECT COUNT from MS Access to a JTable with DButils

I have a JDBC:ODBC connection to a MS Access Database which populates a JTable with DButils. My basic SQL queries work fine until I try the COUNT function and then I get errors when trying to populate my JTable. The query works fine to populate a JTextArea so I know the query is ok.
My code is below any help would be greatly appreciated.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class table {
Connection con;
Statement st;
ResultSet rs;
public table(){
connect();
}
public void connect(){
JTable tbl = new JTable();
tbl.setDefaultEditor(Object.class, null);
JFrame resFrame = new JFrame("Results");
resFrame.setLayout(null);
resFrame.setSize(525, 445);
resFrame.setVisible(true);
JScrollPane tsp = new JScrollPane(tbl);
tsp.setLocation(20, 20);
resFrame.add(tsp);
tbl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tsp.setSize(370,375);
String sql = "SELECT Club, COUNT('memberID') AS total FROM Members_Table, Club_Table WHERE Club_Table.clubID=Members_Table.clubID GROUP BY Club";
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:ITUKdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery(sql);
tbl.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
}
}
}
The error I get is below
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3906)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:5697)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:353)
at sun.jdbc.odbc.JdbcOdbcResultSet.getObject(JdbcOdbcResultSet.java:1677)
at net.proteanit.sql.DbUtils.resultSetToTableModel(DbUtils.java:28)
at trial.table.connect(table.java:53)
at trial.table.<init>(table.java:22)
at trial.ITUKSQL.main(ITUKSQL.java:212)
Sorted had to remove
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE
From
st = con.createStatement();

Categories