Im trying to populate JTable with MySql data. Thing is when i run Login class, i receive message "java.SQLException: No value specified for parameter 2" and when i run JTable class I keep receiving java.lang.NullPointerException error. I have three classes : 1-Connection to DB:
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class javaconnect {
Connection conn = null;
public static Connection ConnecrDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb",
"root", "root");
JOptionPane.showMessageDialog(null, "Connected");
return con;
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
return null;
}
}
The second class is login frame:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.*;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JFrameLogIn extends JFrame {
Connection conn =null;
ResultSet rs = null;
PreparedStatement pst = null;
private JPanel contentPane;
private JPasswordField txt_Password;
private JTextField txt_Username;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameLogIn frame = new JFrameLogIn();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrameLogIn() {
conn=javaconnect.ConnecrDB();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 375, 214);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setFont(new Font("Tahoma", Font.BOLD, 13));
lblUsername.setBounds(126, 45, 80, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 13));
lblPassword.setBounds(126, 82, 69, 14);
contentPane.add(lblPassword);
txt_Password = new JPasswordField();
txt_Password.setBounds(218, 82, 109, 20);
contentPane.add(txt_Password);
txt_Username = new JTextField();
txt_Username.setBounds(216, 43, 111, 20);
contentPane.add(txt_Username);
txt_Username.setColumns(10);
JButton cmd_Login = new JButton("Login");
cmd_Login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql = "Select * from clients where username=? and password=?";
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txt_Username.getText());
pst.setString(1, txt_Password.getText());
rs = pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password are correct");
}
else {
JOptionPane.showMessageDialog(null, "Username and Password are not correct");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
cmd_Login.setBounds(218, 125, 80, 23);
contentPane.add(cmd_Login);
}
}
and the last one is JTable
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class JTable1 extends JFrame {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
private JPanel contentPane;
private JTable table_Admins;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JTable1 frame = new JTable1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JTable1() {
conn = javaconnect.ConnecrDB();
UpdateTable ();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table_Admins = new JTable();
table_Admins.setBounds(30, 28, 378, 54);
contentPane.add(table_Admins);
}
private void UpdateTable () {
try {
String sql = "SELECT *FROM menu";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I am trying to figure out what is the problem but cannot find the solution. Connection works. I would really appreciate your help in fixing this error.
The second parameter in your PreparedStatment is not set. You should replace
pst.setString(1, txt_Password.getText());
with
pst.setString(2, txt_Password.getText());
Edit: Note that JPassword.getText() is deprecated meaning that you should no longer use it. getPassword() is provided in its place:
pst.setString(2, new String(txt_Password.getPassword()));
you can add a check to the code
rs = pst.executeQuery();
if (rs!=null){
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username and Password are correct");
}
else {
JOptionPane.showMessageDialog(null, "Username and Password are not correct");
}
}
And Also in your JTable1 class
if (rs!=null)
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
private void UpdateTable () {
conn = javaconnect.ConnecrDB();// connection and query should be in same place
try {
String sql = "SELECT *FROM menu";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
table_Admins.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
Related
I use SQLite. I have 2 JFrames. 1st is consists of table and "Load data", "Edit data". Click on Edit make the new, 2nd JFrame to appear. I want my table to be updated after I make some changes with a help of class Edit. How do I make it? One idea is to use ActionListener so that after I click save, delete or update buttons in JFrame2 method of Jframe 1, which stays for updating of the table(using query), is called. I have tried, but it does not work. I do not want the method of the 1 Jframe to be called in 2nd Jframe, I want this method to be called in 1st Jframe. What are possible solutions?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.*;
public class Diary extends JFrame {
private JPanel contentPane;
JTable table;
private JButton btnLoadData;
public void refreshTabel(){
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Diary frame = new Diary();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Diary() {
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1250, 650);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(34, 58, 1182, 530);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
btnLoadData = new JButton("Load data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnLoadData.setBounds(33, 17, 117, 29);
contentPane.add(btnLoadData);
JButton btnAddData = new JButton("Edit");
btnAddData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddData nw = new AddData();
nw.addData();
refreshTabel();
}
});
btnAddData.setBounds(153, 17, 117, 29);
contentPane.add(btnAddData);
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.sun.glass.events.WindowEvent;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class AddData extends JFrame {
private JPanel contentPane;
private JTextField Date;
private JTextField ExerciseName;
private JTextField Weight;
private JTextField Sets;
private JTextField Reps;
/**
* Launch the application.
* #return
*/
public static void addData() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddData frame = new AddData();
frame.setVisible(true);
frame.setAlwaysOnTop(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField Exercise;
private JTextField N;
/**
* Create the frame.
*/
public AddData() {
setTitle("Edit");
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 465, 368);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDate = new JLabel("Date");
lblDate.setBounds(29, 49, 61, 16);
contentPane.add(lblDate);
JLabel ExerciseLabel = new JLabel("Exercise");
ExerciseLabel.setBounds(29, 88, 90, 16);
contentPane.add(ExerciseLabel);
JLabel lblNewLabel_1 = new JLabel("Sets");
lblNewLabel_1.setBounds(29, 169, 61, 16);
contentPane.add(lblNewLabel_1);
JLabel lblReps = new JLabel("Reps");
lblReps.setBounds(29, 213, 61, 16);
contentPane.add(lblReps);
JLabel lblWeight = new JLabel("Weight");
lblWeight.setBounds(29, 126, 61, 16);
contentPane.add(lblWeight);
Date = new JTextField();
Date.setBounds(169, 56, 150, 26);
contentPane.add(Date);
Date.setColumns(10);
ExerciseName = new JTextField();
ExerciseName.setBounds(169, 60, 150, 26);
contentPane.add(ExerciseLabel);
ExerciseName.setColumns(10);
Weight = new JTextField();
Weight.setBounds(169, 132, 150, 26);
contentPane.add(Weight);
Weight.setColumns(10);
Sets = new JTextField();
Sets.setBounds(169, 170, 150, 26);
contentPane.add(Sets);
Sets.setColumns(10);
Reps = new JTextField();
Reps.setBounds(169, 208, 150, 26);
contentPane.add(Reps);
Reps.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "insert into Diary (Date, Exercise, Weight, Sets, Reps) values (?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, Date.getText());
pst.setString(2, Exercise.getText());
pst.setString(3, Weight.getText());
pst.setString(4, Sets.getText());
pst.setString(5, Reps.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnSave.setBounds(29, 261, 117, 29);
contentPane.add(btnSave);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "update Diary set N ='"+N.getText()+"', Exercise ='"+Exercise.getText()+"', Weight ='"+Weight.getText()+"', Sets ='"+Sets.getText()+"', Reps ='"+Reps.getText()+"' where N ='"+N.getText()+"' ";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Updated");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnUpdate.setBounds(176, 261, 117, 29);
contentPane.add(btnUpdate);
Exercise = new JTextField();
Exercise.setBounds(169, 94, 150, 26);
contentPane.add(Exercise);
Exercise.setColumns(10);
N = new JTextField();
N.setBounds(169, 18, 150, 26);
contentPane.add(N);
N.setColumns(10);
JLabel lblN = new JLabel("N");
lblN.setBounds(29, 23, 61, 16);
contentPane.add(lblN);
JButton Delete = new JButton("Delete");
Delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from Diary where N = '"+N.getText()+"'";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
Delete.setBounds(305, 261, 117, 29);
contentPane.add(Delete);
}
}
I'm designing a database that can be accessed through a GUI, I have three classes Main, Database and GUI, When I run the main I get an error and the GUI closes followed by a brief error message which I cannot read, not sure where this is going wrong as i believe it can be a number of issues. Thanks for all your help :)
Here is my main class
public class MainApplication {
#SuppressWarnings("unused")
public static void main(String[] args) {
VideoStoreGUI window = new VideoStoreGUI();
}
}
My Database Class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import javax.swing.JOptionPane;
#SuppressWarnings("unused")
public class DataBase {
static Connection con = null;
static Statement stmt = null;
static ResultSet rs = null;
static Scanner in = new Scanner(System.in);
public void close_connection() {
try
{
con.close();
System.out.println("Database Connections Succesully Closed.");
}
catch (SQLException sqle)
{
System.out.println("Error: failed to close the database");
}
}
public static void addMember(int member_id, String name, String address) // Adding a Member to the Database.
{
try {
String str = "INSERT INTO members (member_id, name, address) values(" + member_id + ", '" + name + "', '"
+ address + "');";
int rows = stmt.executeUpdate(str);
System.out.println("Success in adding member");
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error: Could not add member");
}
}
public static void initialize_database() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/videostore";
con = DriverManager.getConnection(url, "root", "admin");
stmt = con.createStatement();
} catch (Exception e) {
System.out.println("Error: Failed to connect to database\n" + e.getMessage());
}
}
public DataBase()
{
initialize_database();
}
}
and my GUI class:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JMenuBar;
public class VideoStoreGUI extends JFrame {
private JFrame frame;
DataBase my_database;
private JPanel contentPane;
private JTextField textMemberID;
private JTextField textMemberName;
private JTextField textMemberAddress;
/**
* Create the frame.
*/
public VideoStoreGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 400);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 31, 232, 240);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("Members", null, panel, null);
panel.setLayout(null);
JLabel labelMemberID = new JLabel("Members ID");
labelMemberID.setBounds(10, 11, 85, 14);
panel.add(labelMemberID);
JLabel labelMemberName = new JLabel("Members Name");
labelMemberName.setBounds(10, 36, 85, 14);
panel.add(labelMemberName);
JLabel labelMemberAddress = new JLabel("Members Address");
labelMemberAddress.setBounds(10, 61, 85, 14);
panel.add(labelMemberAddress);
textMemberID = new JTextField();
textMemberID.setBounds(131, 8, 86, 20);
panel.add(textMemberID);
textMemberID.setColumns(10);
textMemberName = new JTextField();
textMemberName.setColumns(10);
textMemberName.setBounds(131, 33, 86, 20);
panel.add(textMemberName);
textMemberAddress = new JTextField();
textMemberAddress.setColumns(10);
textMemberAddress.setBounds(131, 58, 86, 20);
panel.add(textMemberAddress);
JButton buttonAddMember = new JButton("Add Member");
buttonAddMember.setBounds(10, 86, 102, 23);
panel.add(buttonAddMember);
JButton buttonRemoveMember = new JButton("Add Member");
buttonRemoveMember.setBounds(115, 86, 102, 23);
panel.add(buttonRemoveMember);
JButton buttonSearchMember = new JButton("Add Member");
buttonSearchMember.setBounds(66, 120, 102, 23);
panel.add(buttonSearchMember);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("Products", null, panel_1, null);
}
}
I see only one place where you can get popup. You can keep it if you like but add system output and be sure about your message:
catch (SQLException sqle) {
System.out.writeln("Exception:"+sqle);
JOptionPane.showMessageDialog(null, "Error: Could not add member");
}
Based on place of this message I think you have wrong sql or database. I would suggest that you print your sql and results of it too.
The main reason this was not working for me was because I had removed setVisable(true) from the GUI and forgot to add it back to the method, I was then receiving an Error "AWT-EventQueue-0" this was to do with the way my database connection was set up, removing and adding the JDBC driver again resolved this.
I have 2 class .1 for GUI.1 from others.
LoginUser.java
package login;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import database.DatabaseConnection;
public class LoginUser{
public int doLogin(String username, String password) throws Exception
{
int level =0;
DatabaseConnection databaseConnection = new DatabaseConnection();
Connection con = databaseConnection.getConnection();
String sql ="select level from staff where username=? and password=?";
PreparedStatement ps =con.prepareStatement(sql);
//no 1 and two refer to ? at String sql =...
//Tukar String pada int
ps.setString(1, username);
//int iPassword = Integer.parseInt(password);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
level = rs.getInt(1);
}
//must close all connection
rs.close();ps.close();con.close();
return level;
}
public static void main(String[] args) {
//test sama ada login berjaya atau tak?
LoginUser lgn = new LoginUser();
try {
int level =lgn.doLogin("1008", "test123");
System.out.println("Access Level : "+level);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Another one is for GUI class
LoginInterface.java
package login;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;
import java.awt.Color;
import login.LoginUser;
public class LoginInterface {
private JFrame frame;
private JTextField txtStaffID;
private JPasswordField txtPassword;
/**
* Launch the application.
*/
public static void login() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginInterface window = new LoginInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public LoginInterface() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 678, 421);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblStaffId = new JLabel("Username :");
lblStaffId.setForeground(Color.BLACK);
lblStaffId.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblStaffId.setBounds(108, 158, 89, 23);
frame.getContentPane().add(lblStaffId);
txtStaffID = new JTextField();
txtStaffID.setBounds(207, 160, 200, 23);
frame.getContentPane().add(txtStaffID);
txtStaffID.setColumns(10);
JLabel lblPassword = new JLabel("Password :");
lblPassword.setForeground(Color.BLACK);
lblPassword.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblPassword.setBounds(108, 192, 101, 49);
frame.getContentPane().add(lblPassword);
JButton btnLogIn = new JButton("LOGIN");
btnLogIn.setBackground(new Color(0, 206, 209));
btnLogIn.setForeground(new Color(0, 0, 0));
btnLogIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoginUser lgn = new LoginUser();
try {
String username =txtStaffID.getText();
#SuppressWarnings("deprecation")
String password = txtPassword.getText();
int level =lgn.doLogin(username, password);
if(level == 1)
{
JOptionPane.showMessageDialog(null, "You successfully login");
}
else
{
JOptionPane.showMessageDialog(null, "Your password or username incorrect");
}
System.out.println("Access Level : "+level);
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "Please insert your username and password");
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnLogIn.setFont(new Font("Times New Roman", Font.PLAIN, 16));
btnLogIn.setBounds(283, 272, 113, 34);
frame.getContentPane().add(btnLogIn);
txtPassword = new JPasswordField();
txtPassword.setBounds(207, 208, 200, 20);
frame.getContentPane().add(txtPassword);
}
}
I use PHPmyadmin and XAMPP as for database.Please help me :(
I cant run LoginInterface.I dont know why.Is something wrong on my eclipse luna?
Its only display for running LoginUser.java
You never called LoginInterface.login(); Just add it to your main method.
so I am working to create a functioning GUI that can retrieve info from a database (in this case I'm using Oracle 11g XE) using JDBC to do things such as populate a JTable (built using WindowBuilder).
My Oracle DB Server is running and I can successfully connect to it, however when I try and execute a query to be passed to the DB something goes wrong.
Here is my Connection class, just used to connect to the DB:
import java.sql.*;
import javax.swing.*;
public class OracleConnection {
static Connection con = null;
public static Connection dbConnector() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:XE", "system", "system");
JOptionPane.showMessageDialog(null, "Connection Successful!");
} catch (Exception x) {
JOptionPane.showMessageDialog(null, "Connection Unsuccessful.");
}
return null;
}
public static void main(String[] args) {
dbConnector();
}
}
This works (at least to my knowledge it is because I am prompted with a "Connection Successful!" message)
Now here my GUI class (only other class at the moment):
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.*;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import net.proteanit.sql.DbUtils;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Management {
private JFrame frame;
private JTable tableDownloads;
private JPanel panelMenu;
private JPanel panelDown;
private JPanel panelUp;
private JPanel panelUtility;
private JTable tableUploads;
private JTable tableUtilities;
ResultSet rs = null;
PreparedStatement pat = null;
Connection conn = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Management window = new Management();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Management() {
conn = OracleConnection.dbConnector();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
//CREATES ALL FRAMES / PANELS / BUTTONS / SCROLLPANES / LABELS
//I CUT A LOT OF UN-NEEDED STUFF OUT TO SAVE ROOM
//CREATING FRAMES
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
//CREATING PANELS
final JPanel panelMenu = new JPanel();
frame.getContentPane().add(panelMenu, "name_13312291634045");
panelMenu.setLayout(null);
final JPanel panelDown = new JPanel();
frame.getContentPane().add(panelDown, "name_13314999633769");
panelDown.setLayout(null);
panelDown.setVisible(false);
//CREATING TABLES
tableDownloads = new JTable();
scrollPaneDownloads.setViewportView(tableDownloads);
//CREATING BUTTONS
JButton btnDownloads = new JButton("Downloads");
btnDownloads.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panelMenu.setVisible(false);
panelDown.setVisible(true);
generateDownloads();
}
});
btnDownloads.setFont(new Font("Cambria", Font.BOLD, 14));
btnDownloads.setBounds(32, 104, 122, 39);
panelMenu.add(btnDownloads);
JButton btnBackDown = new JButton("Back to Menu");
btnBackDown.setFont(new Font("Cambria", Font.PLAIN, 13));
btnBackDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panelDown.setVisible(false);
panelMenu.setVisible(true);
}
});
btnBackDown.setBounds(323, 239, 109, 23);
panelDown.add(btnBackDown);
//CREATING LABELS
JLabel lblDownloaduploadAndUtility = new JLabel("Download/Upload and Utility Manager");
lblDownloaduploadAndUtility.setFont(new Font("Cambria", Font.BOLD, 20));
lblDownloaduploadAndUtility.setBounds(48, 11, 370, 39);
panelMenu.add(lblDownloaduploadAndUtility);
JLabel lblDownloadsTable = new JLabel("Downloads Table");
lblDownloadsTable.setFont(new Font("Cambria", Font.BOLD, 24));
lblDownloadsTable.setBounds(122, 0, 196, 29);
panelDown.add(lblDownloadsTable);
}
//METHOD TO GENERATE DOWNLOADS TABLE ******NOT WORKING******
private void generateDownloads() {
try {
String query = "SELECT * FROM DOWNLOADS";
pat = conn.prepareStatement(query); //******** FAILS HERE ********
rs = pat.executeQuery();
tableDownloads.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace();
}
}
}
It seems to break on pat = conn.prepareStatement(query);
The error I am getting is...
at Management.generateDownloads(Management.java:207) at
Management.access$1(Management.java:204) at
Management$2.actionPerformed(Management.java:115) at
javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at
javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at
javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at
javax.swing.DefaultButtonModel.setPressed(Unknown Source) at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown
Source)...
and continues on for many more lines of similar errors..
I can't seem to figure out any reason why it is not properly communicating with the DB. Any help would be GREATLY appreciated guys!
But your dbConnector() method always returns null.
Perhaps you want it to do this instead:
public static Connection dbConnector() {
if (con == null) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:XE", "system", "system");
JOptionPane.showMessageDialog(null, "Connection Successful!");
} catch (Exception x) {
JOptionPane.showMessageDialog(null, "Connection Unsuccessful.");
}
}
return con;
}
I have a textbox which sent something to database and jtable list the values from database. But when i add something to database. Jtable dont show it in same time. when i close the program and debug again, it shows that time. I want Jtabel to show textbox value when i click the save button. How can i create a dynamic jtable?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Topic extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frmTopic;
JPanel pnl, pnl_generaltopic;
static JTextField txt_topic;
JLabel lbl_topicNme, lbl_topicpage;
JButton btn_close, btn_update, btn_save;
public static Connection con = null;
public static ResultSet rs = null;
public static Statement st = null;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
private JScrollPane scrollPane;
private static JTable table;
public Topic() {
pnl_generaltopic = new JPanel();
pnl_generaltopic.setBackground(Color.lightGray);
pnl_generaltopic.setLayout(null);
frmTopic = new JFrame("Topic");
frmTopic.addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent arg0) {
con = Dbconnect.conect();
}
});
frmTopic.setTitle("E-TEST");
frmTopic.setBounds(100, 100, 500, 500);
frmTopic.setVisible(true);
frmTopic.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTopic.getContentPane().setLayout(new BorderLayout(0, 0));
frmTopic.getContentPane().add(pnl_generaltopic);
topicPanel();
topicTable();
}
public void topicPanel() {
JPanel panel_addingNewTopic = new JPanel();
panel_addingNewTopic.setBounds(10, 0, 464, 203);
pnl_generaltopic.add(panel_addingNewTopic);
panel_addingNewTopic.setLayout(null);
btn_save = new JButton("Save");
btn_save.setBounds(65, 166, 67, 23);
panel_addingNewTopic.add(btn_save);
btn_update = new JButton("Update");
btn_update.setBounds(142, 162, 90, 30);
panel_addingNewTopic.add(btn_update);
btn_close = new JButton("Close");
btn_close.setBounds(240, 162, 90, 30);
panel_addingNewTopic.add(btn_close);
txt_topic = new JTextField();
txt_topic.setBounds(65, 59, 270, 71);
panel_addingNewTopic.add(txt_topic);
lbl_topicNme = new JLabel("Topic Name");
lbl_topicNme.setBounds(10, 65, 150, 59);
panel_addingNewTopic.add(lbl_topicNme);
lbl_topicpage = new JLabel("Topic Page");
lbl_topicpage.setBounds(10, 11, 300, 20);
panel_addingNewTopic.add(lbl_topicpage);
lbl_topicpage.setFont(new Font("arial", Font.BOLD, 15));
btn_close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmTopic.dispose();
}
}
);
btn_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
st = con.createStatement();
String sorgu = "insert into topic " + "(topicname)"
+ "VALUES ('" + txt_topic.getText() + "')";
st.executeUpdate(sorgu);
JOptionPane.showMessageDialog(Topic.this, "Topic was added");
} catch (Exception s) {
System.out.print(s.getMessage());
}
}
}
);
}
public void topicTable() {
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 226, 464, 190);
pnl_generaltopic.add(scrollPane);
Vector<String> headers = new Vector<String>();
headers.add("Topic Name");
getData();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
scrollPane.setColumnHeaderView(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//table=new JTable(model);
//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
header_size();
//JScrollPane scroll = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pack();
setResizable(false);
setVisible(true);
}
/**
* Setting the particular Column Size in JTable
*/
public static void header_size() {
TableColumn column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(350);
}
/**
* Fetching Data From MySql Database
* and storing in a Vector of a Vector
* to Display in JTable
*/
private static void getData() {
// Enter Your MySQL Database Table name in below Select Query.
String str = "select * from topics";
Connection con;
ResultSet rs;
Statement st;
try {
con = DriverManager.getConnection("jdbc:mysql://" + "localhost:3306/database", "root", "1234");
st = con.createStatement();
rs = st.executeQuery(str);
while (rs.next()) {
Vector<String> d = new Vector<String>();
d.add(rs.getString("topicname"));
d.add("\n\n\n\n\n\n\n");
data.add(d);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Topic topic = new Topic();
topic.setVisible(false);
}
}
You can use the addRow(...) method of the DefaultTableModel to dynamically add a row of data in the model.
So if the update to your database is successful, then you would invoke the addRow() method.
Also, you should use a PreparedStatement when using SQL. It will make creating the SQL easier since you don't need to worry about the delimiters. Simple example to give you an idea:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, "Name1" );
stmt.setString( 2, textField.getText() );
stmt.executeUpdate();