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;
}
Related
I am trying to create a program that will generate student info within a table. I have created a database within SQLite studio and a table named data. I also have successfully connected the database to my program, however, when the program is ran, there is an sql error saying the table is missing. Please advise.
import java.sql.*;
import javax.swing.*;
public class connection {
Connection conn = null;
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:\\Macintosh HD\\Users\\ethantang\\Desktop\\eclipse-workspace~\\FBLA project\\students.sqlite");
JOptionPane.showMessageDialog(null, "Connected");
return conn;
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
import java.awt.BorderLayout;
import java.sql.*;
import javax.swing.*;
import java.awt.EventQueue;
import net.proteanit.sql.DbUtils;
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.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class database extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
database frame = new database();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connect = null;
/**
* Create the frame.
*/
public database() {
connect = connection.dbConnector();
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);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 45, 438, 227);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JButton btnNewButton = new JButton("Load Database");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "select * from data";
PreparedStatement pst = connect.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception a){
a.printStackTrace();
}
}
});
btnNewButton.setBounds(167, 6, 117, 29);
contentPane.add(btnNewButton);
}
}
I created a program with a few lines of code after getting some advice her on Stackoverflow. My problem is that I can't connect to the database. I get an error called: [SQLITE_ERROR] SQL error or missing database (no such table: PasswordTable).
I created the database via SQLite and also get a successfull connection but cannot insert data.
The database in SQLiteManager is called MyDB.sqlite and the table is called PasswordTable
...I am thankful for any help I can get :)
Also: Did I do the implementation of the inner class right? Is this appropriate?
Code is as follows:
import javax.swing.*;
public class Main {
public static void main (String [] args) {
JFrame frame = new JFrame ();
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(700, 300);
frame.add(new FrameFunctionality ());
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class FrameFunctionality extends JPanel {
JLabel label1;
JTextField tf1;
JButton but1;
Database db1;
public FrameFunctionality() {
setLayout(null);
//----Add a label to the frame
label1 = new JLabel("Passwort eingeben:");
label1.setBounds(10, 20, 150, 40);
add (label1);
//-------Add a tf to the frame
tf1 = new JTextField ();
tf1.setBounds(10, 50, 150, 40);
add (tf1);
//---Add a button to the frame
but1 = new JButton ("Save");
but1.setBounds(10, 100, 100, 50);
but1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
db1 = new Database ();
db1.insertData();
}
});
add (but1);
}
public class Database { //Inner Class
Connection con = null;
DriverManager man1 = null;
PreparedStatement pst = null;
public Database () {
//------Connect to the database
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:MyDB.sqlite");
System.out.println("Connection: Ok!");
} catch (Exception e) {
System.out.println("Error1: " + e.getMessage());
}
}
//Insert data into the database
public void insertData () {
try {
String query = "INSERT INTO PasswordTable (Passwort) VALUES
(?)";
pst = con.prepareStatement(query);
pst.setString(1, tf1.getText());
pst.execute();
}catch (Exception e) {
System.out.println("Error2: " + e.getMessage());
}
}
}
}
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.
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();
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);
}