Jtable how to display data from mysql in different Columns - java

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 :)

Related

Can`t make insert in Oracle database from JSF Java web app

I have a JSF webapp and I encountered one problem. I want to take data that is from one table and is inserted in a datatable and insert it into a log table in the database.
I did the connection with the database but it doesn't show any errors and it doesn't insert anything.
I went in with the debugger from netbeans and the variables that I want to insert have values. I do not know where the problem is.
Here is the code:
package com.spv.raport;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleDataSource;
#Named(value = "dateBean")
#RequestScoped
public class DateBean {
private List<Date> dateList = new ArrayList<>();
public DateBean() throws ClassNotFoundException, SQLException {
String host = "jdbc:oracle:thin:#xxx:1521:xxx";
String user = "xxx";
String pass = "xxx";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(host, user, pass);
Statement stmt = con.createStatement();
String sql = "select utilizator, tip_cerere, parametri, stare from
cereri where tip_cerere='D394' and utilizator='44192556' ";
ResultSet rs = stmt.executeQuery(sql);
String u = null;
String t = null;
String p = null;
String s = null;
String d = null;
while(rs.next()) {
u = rs.getString("utilizator");
t = rs.getString("tip_cerere");
p = rs.getString("parametri");
s = rs.getString("stare");
// d = rs.getString("creation_date");
dateList.add(new Date(u,t,p,s));
}
String host2 = "jdbc:oracle:thin:#xxx:xxx";
String user2 = "xxx";
String pass2 = "xxx";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con2 = DriverManager.getConnection(host2, user2, pass2);
Statement stmt2 = con2.createStatement();
String sql2 = "insert into SPV_RAPORT_LOG values ('serban', '123',
'parametru_test')";
stmt2.executeUpdate(sql);
} catch(SQLException se) {System.out.println(se);}
catch(Exception e) {System.out.println(e);}
}
public List<Date> getDateList() {
return dateList;
}
}
The database host and name and user and passwords are put intentionally with xxx to hide them.
I am a beginner and I do not have any idea why it doesn`t insert the test statement into the database table

Writing data into MySQL table with JavaFX

I have linked up a database to my Java application using the JDBC in Netbeans.
But whenever I try to write something from a TextField to a MySQL table, it doesn't work.
I have a pre-made class to make the database connection.
Here is my database class:
package testswitch;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Maarten
*/
public class Database {
public final static String DB_DRIVER_URL = "com.mysql.jdbc.Driver";
public final static String DB_DRIVER_PREFIX = "jdbc:mysql://";
private Connection connection = null;
public Database(String dataBaseName, String serverURL, String userName, String passWord) {
try {
// verify that a proper JDBC driver has been installed and linked
if (!selectDriver(DB_DRIVER_URL)) {
return;
}
if (serverURL == null || serverURL.isEmpty()) {
serverURL = "localhost:3306";
}
// establish a connection to a named Database on a specified server
connection = DriverManager.getConnection(DB_DRIVER_PREFIX + serverURL + "/" + dataBaseName, userName, passWord);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
private static boolean selectDriver(String driverName) {
// Selects proper loading of the named driver for Database connections.
// This is relevant if there are multiple drivers installed that match the JDBC type.
try {
Class.forName(driverName);
// Put all non-prefered drivers to the end, such that driver selection hits the first
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver d = drivers.nextElement();
if (!d.getClass().getName().equals(driverName)) {
// move the driver to the end of the list
DriverManager.deregisterDriver(d);
DriverManager.registerDriver(d);
}
}
} catch (ClassNotFoundException | SQLException ex) {
logException(ex);
return false;
}
return true;
}
public void executeNonQuery(String query) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(query);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
public ResultSet executeQuery(String query) {
Statement statement;
try {
statement = connection.createStatement();
ResultSet result = statement.executeQuery(query);
return result;
} catch (SQLException eSQL) {
logException(eSQL);
}
return null;
}
private static void logException(Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
}
And here's my JavaFX controller.
What I want is that when the "handle" button is pressed, that the data filled in the TextField gets inserted into the database.
package testswitch;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import testswitch.Database;
/**
*
* #author Maarten
*/
public class gebruikerToevoegenController {
//TextFields
#FXML
private TextField FXVoornaam, FXTussenvoegsel, FXAchternaam, FXGebruikersnaam;
#FXML
private TextField FXWachtwoord, FXEmail, FXTelefoonnummer;
//Boolean checkbox positie
#FXML
private CheckBox ManagerPosition;
#FXML
private Button gebruikerButton;
public final String DB_NAME = "testDatabase";
public final String DB_SERVER = "localhost:3306";
public final String DB_ACCOUNT = "root";
public final String DB_PASSWORD = "root";
Database database = new Database(DB_NAME, DB_SERVER, DB_ACCOUNT, DB_PASSWORD);
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES " + FXVoornaam.getText();
try {
database.executeQuery(query);
} catch (Exception e) {
}
}
}
Thanks in advance
The string in your SQL query doesn't seem to be properly quoted. It's best to use PreparedStatement for this scenario:
public class Database {
public PreparedStatement prepareStatement(String query) throws SQLException {
return connection.prepareStatement(query);
}
...
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES (?);";
PreparedStatement statement = database.prepareStatement(query);
try {
statement.setString(1, FXVoornaam.getText());
statement.executeUpdate();
} catch (Exception e) {
// log info somewhere at least until it's properly tested/
// you implement a better way of handling the error
e.printStackTrace(System.err);
}
}
You have to add like this in JavaFx :
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES ('{FXVoornaam.getText()}') ";
String query = "INSERT INTO testDatabase.Gebruikers(Voornaam)
VALUES('" + FXVoornaam.getText() + "')";

Java: How to return JDBC queries from JcomboBox

package userProfile;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Database extends JFrame implements ActionListener {
JFrame frame;
JButton search, mainMenu;
JComboBox fromLoc, toLoc, fromDate, fromTime;
JLabel fromLabel, toLabel, fromDateLabel, fromTimeLabel;
PreparedStatement ps = null;
Connection link;
ResultSet rs = null;
public Database() {
frame = new JFrame("Make a Reservation");
frame.getContentPane().setLayout(null);
//Arrival date/time comboBoxes and labels
fromDateLabel = new JLabel("Departure Date");
fromDateLabel.setBounds(50,230,100,30);
fromDate = new JComboBox(new String[]{"12/15/2015",
"12/21/2015", "12/21/2015", "12/24/2015"});
fromDate.addActionListener(this);
fromDate.setBounds(50,200,100,30);
/*
fromTimeLabel = new JLabel("Departure Time");
fromTimeLabel.setBounds(160,230,100,30);
fromTime = new JComboBox(new String[]{"13:00","15:00", "15:30", "08:00"});
fromTime.addActionListener(this);
fromTime.setBounds(160,200,100,30);
*/
//Departure label and comboBox
fromLabel = new JLabel("Departure");
fromLabel.setBounds(50,300,100,30);
fromLoc = new JComboBox(new String[]{"Atlanta", "Charleston", "New York", "Los Angeles", "Orlando", "San Francisco"});
fromLoc.addActionListener(this);
fromLoc.setBounds(50,270,100,30);
toLabel = new JLabel("Arrival");
toLabel.setBounds(160,300,100,30);
toLoc = new JComboBox(new String[]{"Atlanta", "Charleston", "New York", "Los Angeles", "Orlando", "San Francisco"});
toLoc.addActionListener(this);
toLoc.setBounds(160,270,100,30);
search = new JButton("Ok");
search.addActionListener(this);
search.setBounds(270,270,100,30);
//adding the buttons in frame
frame.getContentPane().add(fromDateLabel);
frame.getContentPane().add(fromDate);
frame.getContentPane().add(fromTimeLabel);
frame.getContentPane().add(fromTime);
frame.getContentPane().add(fromLabel);
frame.getContentPane().add(fromLoc);
frame.getContentPane().add(toLabel);
frame.getContentPane().add(toLoc);
frame.getContentPane().add(search);
frame.setSize(400,400);
frame.setVisible(true);
try {
// Driver for mysql
Class.forName("com.mysql.jdbc.Driver");
// connection link obj
link = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "root", "root");
// query statement obj
} catch (SQLException sqle) {
System.out.println("An error occurred.Maybe user/password is invalid");
sqle.printStackTrace();
} catch (ClassNotFoundException cfne) {
cfne.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e) {
JComboBox fromLoc = (JComboBox)e.getSource();
String fromL = fromLoc.getSelectedItem().toString();
JComboBox fromDate = (JComboBox)e.getSource();
String fromD = fromDate.getSelectedItem().toString();
JComboBox toLoc = (JComboBox)e.getSource();
String toL = toLoc.getSelectedItem().toString();
ArrayList<Flights> results = new ArrayList<>();
try {
ps = link.prepareStatement("select * from flights where from_date = ? and from_loc = ? and to_loc = ?");
ps.setString(1, fromD);
ps.setString(2, fromL);
ps.setString(3, toL);
rs = ps.executeQuery();
while(rs.next()) {
Flights flight = new Flights();
flight.setFromD(rs.getString("from_date"));
flight.setFromL(rs.getString("from_loc"));
flight.setToL(rs.getString("to_loc"));
results.add(flight);
}
} catch (SQLException sqle) {
System.out.println("An error occurred.Maybe user/password is invalid");
sqle.printStackTrace();
}
}
}
I'm getting an NullPointerException when running this. This program should query database using hard-coded strings from an array in 3 comboBoxes and save returned strings as objects into an ArrayList.
Please help, again
Thanks
I would create a Flight model class and use it as a DTO. So, in your while(rs.next) i would use the the result to instantiate Flight objects and add them to an ArrayList<Flight> which could be returned to where ever you need to use it.
Your 3rd question I'm not quite sure about since i havn't worked a lot with Swing.
Hope my response is helpful to you. If I misunderstood your question please let me know.
EDIT:
A DTO is a Data Transfer Object used for contain and transfer data. So a Flight class could look like this:
public class Flight{
public String fromD;
public String fromL;
public String toL;...
//And so on
//You also need setters and getters
}
Then in your Database class:
ArrayList<Flight> results = new ArrayList<>();
while(rs.next){
Flight flight = new Flight();
flight.setFromD(rs.getString("columnname"));
//Same method for the other variables you need to set.
results.add(flight);
}

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?

Categories