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);
}
}
Related
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;
}
This is My Main class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.JButton;
public class Button extends JFrame {
public JPanel contentPane;
public SaveObject saveObject=new SaveObject();
public table frame1 ;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Button frame = new Button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Button() {
NimbusLookAndFeel laf = new NimbusLookAndFeel();
try {
UIManager.setLookAndFeel(laf);
} catch (UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
frame1=new table();;
JButton btnNewButton = new JButton("SAVE");
btnNewButton.setBounds(151, 99, 120, 52);
contentPane.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveObject.save(frame1);
}
});
}
}
This is My second Class
import java.io.Serializable;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class table implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
public String[] title={"1","2","3","4","5"};
public DefaultTableModel tableModel=new DefaultTableModel(title,0);
JFrame a=new JFrame();
JTable table = new JTable(tableModel) ;
public JScrollPane scrollPane=new JScrollPane();
public Object[] object=new Object[title.length];
public int practiceNumber=0;
public String[] premlesave=new String[100];
public table()
{
scrollPane.setBounds(0, 0, 396, 188);
table.setFillsViewportHeight(true);
a.setVisible(true);
a.add(scrollPane);
} }
And this is My saveobject Class
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.imageio.stream.FileImageInputStream;
public class SaveObject
{
private ObjectOutputStream output;
private ObjectInputStream input;
public void save(Object o)
{
try{
output = new ObjectOutputStream(new FileOutputStream("mm.ser"));
output.writeObject(o);;
output.close();
output.flush();
}
catch(IOException e)
{}
}
}
And now I want use NimbusLookAndFeel laf = new NimbusLookAndFeel(); but this is not Serializable and show error. Why? This means I cant use the NimbusLookAndFeel?
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();
I have a JTabbedPane with 4 tabs. I would like to load 1 tab 1 after another as the tabs uses, refers and retrieves from the same database. And this is causing an issue of "Database is locked" in my application.
Thanks in advance for the help and suggestions :)
This is how I create the JTabbedPane
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBounds(0, 0, 450, 300);
tabbedPane.addTab("tab1", new class1UseDb());
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
tabbedPane.addTab("tab2", new class2UseDb());
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
tabbedPane.addTab("tab3", new class3UseDb());
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
tabbedPane.addTab("tab4", new class());
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
Based on this example, the sscce below simply creates a new panel for each click on the Add button and fills in the result. In a real program, you may want to use a SwingWorker to manage latency and resources.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import org.h2.jdbcx.JdbcDataSource;
/**
* #see https://stackoverflow.com/a/19860170/230513
* #see https://stackoverflow.com/a/15715096/230513
* #see https://stackoverflow.com/a/11949899/230513
*/
public class TabData {
private int n = 1;
private void display() {
JFrame f = new JFrame("TabData");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTabbedPane jtp = new JTabbedPane();
jtp.add(String.valueOf(n), createPane());
f.add(jtp, BorderLayout.CENTER);
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p.add(new JButton(new AbstractAction("Add") {
#Override
public void actionPerformed(ActionEvent e) {
jtp.add(String.valueOf(++n), createPane());
jtp.setSelectedIndex(n - 1);
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JPanel createPane() {
JPanel p = new JPanel();
JLabel l = new JLabel();
p.add(new JLabel("Result: "));
p.add(l);
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:file:~/src/java/jdbc/test;IFEXISTS=TRUE");
ds.setUser("sa");
ds.setPassword("");
try {
Connection conn = ds.getConnection();
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT RAND() FROM DUAL");
rs.next();
l.setText(rs.getString(1));
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new TabData().display();
}
});
}
}
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);
}