I finally got the password, the queries, the button and the connection, but how come it Seems I can't seem to log in? what's wrong with my Action Handler? please check my code
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.sql.*;
public class Login extends JFrame {
private JLabel label1, label2;
private JButton submit;
private JTextField textfield1;
private JPasswordField passfield;
private JPanel panel;
public Login() {
setSize(300, 100);
setVisible(true);
label1 = new JLabel("User ID:");
textfield1 = new JTextField(15);
label2 = new JLabel("Password:");
passfield = new JPasswordField(15);
submit = new JButton("Submit");
panel = new JPanel(new GridLayout(3, 1));
panel.add(label1);
panel.add(textfield1);
panel.add(label2);
panel.add(passfield);
panel.add(submit);
add(panel, BorderLayout.CENTER);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}// end login constructor
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
String user = textfield1.getText();
char[] passChars = passfield.getPassword();
Connection conn = Jdbc.dbConn();
PreparedStatement ps = null;
ResultSet rs = null;
String pass = new String(passChars);
if (passChars != null) {
String sql = "SELECT employee_ID,employee_password FROM user where" +
"employee_ID='user' and employee_password=+'pass'";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
if (rs.next()) {
user = rs.getString("employee_id");
pass = rs.getString("employee_password");
JOptionPane.showMessageDialog(null,"Welcome "+user);
} else {
JOptionPane.showMessageDialog(null, "Wrong Input");
}
} catch (Exception e) {
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception ee) {
}
}
}// end actionPerformed
}// End ButtonHandler
}// End of class
}
you have two choices for PreparedStatement, both are correct
1) change String sql = .... definition
String sql = "SELECT employee_ID, employee_password FROM
user WHERE employee_ID = ? AND employee_password = ?";
2) put variables to the SQL statement directly
String sql = "SELECT employee_ID, employee_password FROM user WHERE
employee_ID = '" + user + "' AND employee_password = '" + pass + "'";
Change your select
employee_ID=? and employee_password=?
http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html
Or you can use named parameters
String query = "select * from people where (first_name = :name or last_name
= :name) and address = :address");
NamedParameterStatement p = new NamedParameterStatement(con, query);
p.setString("name", name);
p.setString("address", address);
please rewrite your code like this
if (passChars != null) {
String sql = "SELECT employee_ID,employee_password FROM user where
employee_ID=? and employee_password=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
if (rs.next()) {
user = rs.getString("employee_id");
pass = rs.getString("employee_password");
JOptionPane.showMessageDialog(null,"Welcome "+user);
} else {
JOptionPane.showMessageDialog(null, "Wrong Input");
}
} catch (Exception e) {
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception ee) {
}
}
}
Related
I've recently been trying to write to a Database by taking user input from a GUI and I would like to store that user input from the GUI in a derby database on netbeans. At the moment, I have got some code but it does not seem to be functional as when i run the GUI and start inputting the data that is supposed to be stored in the back end of my program in the database, it does not store that data which is being inputted in the GUI. It does not load any data onto the database!
Here is the code for writing to the Database:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* #author Hammad
*/
public class WritePlayerDB
{
private final DBConnection dbc;
private final Connection conn;
private Statement stmt;
String insertQuery;
public WritePlayerDB()
{
dbc = new DBConnection();
conn = dbc.getConnection();
}
public void writeToPlayerDB()
{
try {
int playerID = 0;
insertQuery = "INSERT INTO 'PLAYERINFO' ('PLAYER_ID', 'PLAYER_NAME', 'PRIZE_WON', 'CORRECT_ANSWERS')" + "VALUES(1,2,3,4)";
this.stmt = conn.createStatement();
this.checkExistedTable("PLAYERS");
PreparedStatement ps = conn.prepareStatement(insertQuery);
CorrectAnswers.correctAnswers[MillionaireGui.moneyCounter] = PrizeMoney.prizeLadder[MillionaireGui.moneyCounter];
ps.setInt(1, playerID++);
ps.setString(2, MillionaireGui.nameField.getText());
ps.setInt(3, PrizeMoney.prizeLadder[MillionaireGui.moneyCounter]);
ps.setInt(4, CorrectAnswers.correctAnswers[MillionaireGui.moneyCounter]);
ps.executeUpdate();
ps.close();
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
}
public void checkExistedTable(String name)
{
try {
DatabaseMetaData dbmd = this.conn.getMetaData();
String[] types = {"TABLE"};
stmt = this.conn.createStatement();
ResultSet rs = dbmd.getTables(null, null, null, types);
while (rs.next()) {
String table_name = rs.getString("TABLE_NAME");
System.out.println(table_name);
if (table_name.equalsIgnoreCase(name)) {
stmt.executeUpdate("Drop table " + name);
System.out.println("Table " + name + " has been deleted.");
break;
}
}
rs.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
and I am calling the writeToPlayerDB() method in the actionListener for my GUI's JTextField as shown below:
nameField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (nameField.getText().equals(""))
{
blankName.setVisible(true);
blankName.setText("PLEASE DON'T LEAVE NAME BLANK");
}
else
{
playerName.setPlayerName(nameField.getText().toUpperCase());
WritePlayerDB wdb = new WritePlayerDB();
wdb.writeToPlayerDB();
blankNamePanel.setVisible(false);
introRuleScreen();
}
}
});
Would appreciate if i could get a hand with this as I have been stuck on it for a long time!
There's not enough information to go by to truely understand what your core problem is, how ever...
static is not a good idea, especially when you're dealing with UI elements, as you might have more then one instance of the UI and then you can no longer determine which instance of the element you're actually referencing. Better to make use of dependency injection and pass the information to the method directly.
+ "VALUES(1,2,3,4)" s not how you use PreparedStatement, see Using Prepared Statements for more details
Also...
int playerID = 0;
//...
ps.setInt(1, playerID++);
means that the player id is ALWAYS 0 (the ++ is a postfix operation; assignment first, addition second). In fact, you should avoid at all costs, manually creating record ids like this and the database should be making use of "auto incrementing" values internally. See Autogenerated keys for more details.
For simplicty, I use the H2 Database Engine for the following example. It should otherwise work with Derby, but you'll want to remove the createTables method
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringJoiner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
DatabaseManager db = new DatabaseManager();
db.open();
JFrame frame = new JFrame();
frame.add(new MainPane(db));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public class MainPane extends JPanel {
private JTextField nameField;
private JSpinner moneyCounter;
public MainPane(DatabaseManager database) {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(4, 4, 4, 4);
add(new JLabel("Name: "), gbc);
gbc.gridy++;
add(new JLabel("Counter: "), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
nameField = new JTextField(10);
moneyCounter = new JSpinner(new SpinnerNumberModel(0, 0, 100, 10));
add(nameField, gbc);
gbc.gridy++;
add(moneyCounter, gbc);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
if (name.isBlank()) {
JOptionPane.showMessageDialog(MainPane.this, "Name can not be blank", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
int playerId = database.savePlayer(name, (int) moneyCounter.getValue());
List<String> results = database.getPlayerById(playerId);
StringJoiner sj = new StringJoiner("<br>", "<html>", "</html>");
for (String text : results) {
sj.add(text);
}
JOptionPane.showMessageDialog(MainPane.this, sj.toString(), "Success", JOptionPane.PLAIN_MESSAGE);
} catch (SQLException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(MainPane.this, "Failed to create player record", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
add(btnSave, gbc);
}
}
public class DatabaseManager {
private Connection connection;
protected void createTables() throws SQLException {
String cmd = "create table IF NOT EXISTS PLAYERINFO ("
+ "PLAYER_ID bigint GENERATED BY DEFAULT AS IDENTITY(START WITH 0) PRIMARY KEY,"
+ "PLAYER_NAME varchar(255) not null,"
+ "PRIZE_WON int not null,"
+ "CORRECT_ANSWERS int not null"
+ ")";
try (Statement stmt = connection.createStatement()) {
stmt.execute(cmd);
}
}
public void open() throws SQLException {
if (connection != null && !connection.isClosed()) {
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.WARNING, null, ex);
}
}
connection = DriverManager.getConnection("jdbc:h2:~/test");
createTables();
}
public void close() throws SQLException {
if (connection == null) {
return;
}
try {
if (connection.isClosed()) {
connection = null;
}
connection.close();
} finally {
connection = null;
}
}
public int savePlayer(String name, int counter) throws SQLException {
String cmd = "insert into PLAYERINFO (PLAYER_NAME, PRIZE_WON, CORRECT_ANSWERS) values (?, ?, ?)";
try (PreparedStatement stmt = connection.prepareStatement(cmd, Statement.RETURN_GENERATED_KEYS)) {
Random rnd = new Random();
stmt.setString(1, name);
stmt.setInt(2, rnd.nextInt(100) + 1);
stmt.setInt(3, counter);
if (stmt.executeUpdate() != 1) {
throw new SQLException("Unexpectedly modified more then one row");
}
try (ResultSet rs = stmt.getGeneratedKeys()) {
if (rs.next()) {
return rs.getInt(1);
}
}
}
throw new SQLException("Failed to create player record");
}
public List<String> getPlayerById(int id) throws SQLException {
String cmd = "select * from playerinfo where PLAYER_ID = ?";
List<String> results = new ArrayList<>(8);
try (PreparedStatement stmt = connection.prepareStatement(cmd)) {
stmt.setInt(1, id);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
String name = rs.getString("PLAYER_NAME");
int prizeWon = rs.getInt("PRIZE_WON");
int correctAnswer = rs.getInt("CORRECT_ANSWERS");
results.add(name + " won " + prizeWon + " with " + correctAnswer + " correct answers");
}
}
}
return results;
}
}
}
Here i am trying to retrieve a image stored in BLOB format and storing it in another table in the same BLOB format only! And one more issue is this that i have a JFrame named WelcomeStaffs from which i have to access the JTextField named subject_txt and staff_txt values and store it in the database.. But those are only blank! Not getting printed in the output, while i print it!
Here is the code of the FaceRecognizer class..
import static cern.jet.math.Bessel.i1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import facedetection.*;
import com.googlecode.javacv.*;
import com.googlecode.javacv.cpp.*;
import com.googlecode.javacpp.Loader;
import com.mysql.jdbc.Connection;
import java.sql.Blob;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FaceRecognizer extends JFrame
{
// GUI components
private FaceRecogPanel facePanel;
private JButton recogBut;
private JTextField nameField; // where the name (and distance info) appears
private JButton done;
private JButton exit;
public FaceRecognizer()
{
super("Face Recognizer");
FaceRecognizer fac;
Container c = getContentPane();
c.setLayout( new BorderLayout() );
// Preload the opencv_objdetect module to work around a known bug.
Loader.load(opencv_objdetect.class);
facePanel = new FaceRecogPanel(this); // the sequence of pictures appear here
c.add( facePanel, BorderLayout.CENTER);
// button for recognizing a highlighted face
done = new JButton("Done");
recogBut = new JButton("Recognize Face");
recogBut.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{ nameField.setText("");
recogBut.setEnabled(false);
facePanel.setRecog();
}
});
done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
WelcomeStaffs wc = new WelcomeStaffs();
Connection con = null;
try{
String url = "jdbc:mysql://localhost:3306/facedetection";
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Conncection Success");
con = (Connection) DriverManager.getConnection(url, "root", "2204");
System.out.println("Database Connected");
}
catch(Exception ex)
{
System.out.println("Exception = "+ex);
}
String nm = nameField.getText().toUpperCase();
String name ="",course="";
System.out.println("Hello im till here!!");
String subject = wc.subject_txt.getText();
String staff = wc.staff_txt.getText();
String day = wc.day_txt.getText();
String date = wc.date_txt.getText();
String time = wc.time_txt.getText();
int roll_no = 0;
System.out.println(subject+staff);
String sql = "SELECT roll_no,name,course,photo FROM students WHERE name=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,nm);
ResultSet rs = ps.executeQuery();
while(rs.next()) //retrieving values from database and storing it!
{
roll_no = rs.getInt("roll_no");
name = rs.getString("name");
course = rs.getString("course");
byte[]imagedata = rs.getBytes("photo");
image = Toolkit.getDefaultToolkit().createImage(imagedata);
format = new ImageIcon(image);
System.out.println("Retrieved Data!!!!!!!");
}
} catch (SQLException ex) {
Logger.getLogger(FaceRecognizer.class.getName()).log(Level.SEVERE, null, ex);
}
try{
if(roll_no == 0 || name.equals("") || course.equals(""))
{
System.out.println("EMPTY");
}
else
{
sql = "INSERT INTO attendance(roll_no, name, course, subject, staff, day, time, date, photo) VALUES(?,?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql);
ps1.setInt(1,roll_no);
ps1.setString(2,name);
ps1.setString(3,course);
ps1.setString(4,subject);
ps1.setString(5,staff);
ps1.setString(6,day);
ps1.setString(7,time);
ps1.setString(8,date);
ps1.setBlob(9, (Blob) format);
int i1 = ps1.executeUpdate();
JOptionPane.showMessageDialog(null,i1+" Data Inserted");
}
}
catch(Exception ec)
{
System.out.println(""+ec);
}
}
});
nameField = new JTextField(20); // for the name of the recognized face
nameField.setEditable(false);
JPanel p = new JPanel();
p.add(recogBut);
p.add( new JLabel("Name: "));
p.add( nameField);
p.add(done);
c.add(p, BorderLayout.SOUTH);
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ facePanel.closeDown(); // stop snapping pics
/*Attendance_Chart ac = new Attendance_Chart();
ac.setVisible(true);*/
System.exit(0);
}
});
pack();
setResizable(false);
setVisible(true);
} // end of FaceRecognizer()
public void setRecogName(final String faceName, final String dist)
// update face name and its distance in the nameField; called from panel
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{ nameField.setText( faceName);
recogBut.setEnabled(true);
}
});
} // end of setRecogName()
// -------------------------------------------------------
public static void main( String args[] )
{
new FaceRecognizer();
}
public ImageIcon format = null;
public Image image = null;
public Blob blob = null;
}
// end of FaceRecognizer class
Here is the output i get!
Conncection Success for Staffs
detection/recognition duration: 9ms
Database Connected for Staffs
Table Created
Conncection Success
Database Connected
Hello im till here!!
Retrieved Data!!!!!!!
java.lang.ClassCastException: javax.swing.ImageIcon cannot be cast to `java.sql.Blob`
Please help!
Thank you!
Im making a project about school management system , i have a jframe to set marks and inside the jframe i have a jtable which is connected to sql database , in the jframe i have a JCombobox with 6 different subjects and in my database i have created 6 tables for the subjects and if any of the subjects are clicked then the jTable will connect to database and change the table to that subject , after its changed if u double click on any row and insert a value then it will automatically update the table in the database , but my problem is that if i select the first option from the jcombox which is English and edit the values then it works fine , but if i select any other option e.g Math or Science , then i try to edit the table then it edits the English table , I commented the English option in the code to see what happens and i saw that it edits only the first option and if u try to change the subjects and edit than it edits the first subject in the combobox , so how can i solve this ? please help
CODE:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
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 java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;
import javax.swing.event.TableModelEvent;
import javax.swing.event.*;
import javax.swing.table.TableModel;
import net.proteanit.sql.DbUtils;
public class Marks implements TableModelListener {
JFrame frame;
JTable table;
JComboBox comboBox;
static Connection connection = null;
static Statement stmt = null;
static ResultSet rs;
String item = "";
String id = "";
String name = "";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Marks window = new Marks();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Marks() throws SQLException {
connection = DriverManager.getConnection("jdbc:odbc:Project");
initialize();
table();
ComboItem();
stateChanged();
Combobox();
item = comboBox.getSelectedItem().toString();
System.out.println("Final Item: "+item);
}
public void table() {
try {
String a = comboBox.getSelectedItem().toString();
//a = a.substring(0, a.length() - 1);
String query = " Select * from " + a;
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
//item = comboBox.getSelectedItem().toString();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void stateChanged(){
itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
System.out.println("Item after stateChanged: " + item);
if (comboBox.getSelectedItem().equals("English")) {
try {
String query = "Select * from English";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "English";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("Math")) {
try {
String query = "Select * from Math";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "Math";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("Science")) {
try {
String query = "Select * from Science;";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "Science";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("History")) {
try {
String query = "Select * from History;";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "History";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("IT")) {
try {
String query = "Select * from IT;";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "IT";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("Geography")) {
try {
String query = "Select * from Geography;";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "Geography";
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
};
}
#Override
public void tableChanged(TableModelEvent e) {
try {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel) e.getSource();
String columnName = model.getColumnName(column);
Object data = model.getValueAt(row, column);
Object roll = model.getValueAt(row, 0);
System.out.println("Subject Changed: " + item);
System.out.println("New Data: " + data.toString());
System.out.println("User Id: " + roll.toString());
System.out.println("Column name: " + columnName);
String query = "UPDATE " + item + " SET " + columnName + " = '"
+ data.toString() + "' WHERE userid='" + roll.toString() + "' ";
PreparedStatement pst;
pst = connection.prepareStatement(query);
pst.executeUpdate();
// pst.close();
} catch (SQLException ex) {
Logger.getLogger(Marks.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
ItemListener itemListener;
public void ComboItem(){
comboBox.addItemListener(itemListener);
}
private void Combobox() {
comboBox.addItemListener(itemListener);
comboBox.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
System.out.println(item);
if (comboBox.getSelectedItem().equals("English")) {
try {
String query = "Select * from English";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "Engish";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("Math")) {
try {
String query = "Select * from Math";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "Math";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("Science")) {
try {
String query = "Select * from Science;";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "Science";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("History")) {
try {
String query = "Select * from History;";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "History";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("IT")) {
try {
String query = "Select * from IT;";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "IT";
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (comboBox.getSelectedItem().equals("Geography")) {
try {
String query = "Select * from Geography;";
PreparedStatement pst = connection.prepareStatement(query);
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
table.getModel().addTableModelListener(new Marks());
item = "Geography";
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.setBounds(100, 100, 600, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setResizable(false);
frame.getContentPane().setLayout(null);
JLabel lblSetMarks = new JLabel("<html><u>Set Marks</u></html>");
lblSetMarks.setHorizontalAlignment(SwingConstants.CENTER);
lblSetMarks.setFont(new Font("Castellar", Font.BOLD, 25));
lblSetMarks.setBounds(218, 11, 159, 22);
frame.getContentPane().add(lblSetMarks);
comboBox = new JComboBox();
comboBox.setFont(new Font("Book Antiqua", Font.PLAIN, 15));
comboBox.setBounds(459, 47, 125, 22);
comboBox.addItem("English");
comboBox.addItem("Geography");
comboBox.addItem("History");
comboBox.addItem("IT");
comboBox.addItem("Math");
comboBox.addItem("Science");
frame.getContentPane().add(comboBox);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 87, 574, 259);
frame.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JLabel lblClass = new JLabel("Date :");
lblClass.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblClass.setBounds(10, 51, 58, 14);
frame.getContentPane().add(lblClass);
JLabel lblSubject = new JLabel("Subject :");
lblSubject.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblSubject.setBounds(391, 49, 58, 18);
frame.getContentPane().add(lblSubject);
}
}
The problem revolves around the use of table.getModel().addTableModelListener(new Marks());, which is creating a new instance of Marks, which your main class, each time you select a new project
This means that when tableChanged is called, it's not dealing with the instance of item which you modified in the original instance, but some other instance, which is ALWAYS set to English
Instead, you should try using something like table.getModel().addTableModelListener(this); instead, but only set it ONCE from within the constructor, otherwise it will be called multiple times, which will degrade the performance of your system...
Be Careful using a TableModelListener, it will be called when a cell is changed, row is changed, added, removed or the entire contents of the table model is changed. You should be trying to determine the actual type of event before trying to update the database, as you could end up updating the data to the wrong tables for the wrong reasons
You should avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify.
It would seriously discourage the use of a KeyListener on a JComboBox (I'd seriously discourage the use of KeyListener generally), it's not the best choice of listener for this case, besides, you now have two ItemListeners and a KeyListener attached to your combobox, all doing the same thing...multiple times...
Get rid of the ItemListener and use an ActionListener instead, ItemListener may be triggered multiple times (once for the deselection of the selected item and once of the selection of the new item) and frankly, you just don't care, you only want to know when it's changed.
Take a look at:
Laying Out Components Within a Container
How to Use Combo Boxes
How to Write an Action Listeners
for more details
I can't seem to figure out how to delete a record from a sqlite database created via java. I was trying to identify the record with the primary id but I just keep getting a null pointer exception. Heres my code:
package userinterface;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import backend.SQLiteDb;
import business.Person;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GUI {
static SQLiteDb db;
public static void main(String[] args) {
final JFrame jframe = new JFrame();
JButton btnEnterInfo = new JButton("Enter Info");
jframe.getContentPane().add(btnEnterInfo, BorderLayout.CENTER);
jframe.setVisible(true);
jframe.setSize(300, 300);
btnEnterInfo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JLabel fullName = new JLabel("Full Name: ");
JTextField nameField = new JTextField();
JLabel age = new JLabel("Age: ");
JTextField ageField = new JTextField();
JLabel address = new JLabel("Address: ");
JTextField addressField = new JTextField();
JLabel salary = new JLabel("Salary: ");
JTextField salaryField = new JTextField();
Object[] ob = { fullName, nameField, age, ageField, address,
addressField,
salary, salaryField };
int result = JOptionPane.showConfirmDialog(null, ob, "Part 5",
JOptionPane.OK_CANCEL_OPTION);
jframe.getContentPane().setLayout(new FlowLayout());
if (result == JOptionPane.OK_OPTION) {
db = new SQLiteDb();
db.createPersonnelTable();
String fullName1 = nameField.getText();
String userAge = ageField.getText();
String userAddress = addressField.getText();
String userSalary = salaryField.getText();
Person person = new Person(fullName1, Integer
.parseInt(userAge), userAddress,
Double.parseDouble(salaryField.getText()));
db.addPerson(person);
String sql = "SELECT * FROM COMPANY";
Statement stmt = null;
try {
java.sql.Statement s;
Connection connection = DriverManager
.getConnection("JDBC:sqlite:Andy.db");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id_col = rs.getInt("ID");
String name = rs.getString("name");
int age1 = rs.getInt("Age");
String address1 = rs.getString("Address");
double salary1 = rs.getInt("Salary");
String output = id_col + " " + name + " " + age1
+ " " + address1 + " " + salary1;
System.out.println(output);
}
delete(3);
rs.close();
} catch (SQLException ee) {
System.out.println("ee error");
ee.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
System.out.println("e1 error");
e1.printStackTrace();
}
}
}
}
}
});
}
public static void viewTable(Connection con, String dbName)
throws SQLException {
}
public static void delete(int id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// connection = DriverManager.getConnection();
preparedStatement = connection.prepareStatement("DELETE FROM person WHERE id = ?");
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
System.out.println("DELETE FROM person WHERE id = ?");
} catch (Exception eeee) {
eeee.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}}
connection is null in your delete method, why wouldn't you get NullPointerException?
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// connection = DriverManager.getConnection(); <--- !!!! This line is commented for some reason, so it is not executed!
preparedStatement = connection.prepareStatement("DELETE FROM person WHERE id = ?");
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
The rest of your code in your delete method looks ok, you just need to initialize your connection variable to something.
A possible solution is to store this variable in a method field instead of a local variable when you are initializing it in your actionPerformed method:
this.connection = DriverManager
.getConnection("JDBC:sqlite:Andy.db");
Then you could use:
preparedStatement = this.connection.prepareStatement("DELETE FROM person WHERE id = ?");
which would re-use the previously initialized connection. (Re-using connection object is a good idea)
I'm trying to make a authorization JFrame to MS Access DB, but query does'nt seems to wirk properly. The idea is to intup login and password, and if one of them isn't correct, get a message. My code always sends me to the exception. Here is my code, maybe someone can help me.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class First {
JFrame frame;
JPanel txt, but;
JButton log, ext;
JTextField login;
JLabel l, p;
JPasswordField pass;
PreparedStatement prepst;
ResultSet res;
public First() {
frame = new JFrame("Authorization");
txt = new JPanel();
but = new JPanel();
log = new JButton("Login");
ext = new JButton("Quit");
login = new JTextField(10);
l = new JLabel("Login:");
p = new JLabel("Password:");
pass = new JPasswordField(10);
frame.setSize(400,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt.add(l);
txt.add(login);
txt.add(p);
txt.add(pass);
frame.add(txt,BorderLayout.NORTH);
but.add(log);
but.add(ext);
frame.add(but,BorderLayout.SOUTH);
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String PathToDataBase = "D:/workspace2/MicrosoftAccessConnection/db";
String DataBase = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
DataBase += PathToDataBase.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection(DataBase,"","");
prepst = con.prepareStatement("SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?");
String lll = login.getText();
String ppp = pass.getText();
prepst.setString(1,lll);
prepst.setString(2, ppp);
res = prepst.executeQuery();
if((test(con,lll,ppp)) == true) {
while(res.next()) {
if((lll.equals(res.getString("LOGIN"))) && (ppp.equals(res.getString("PASSWORD")))) {
lol();
} else {
JOptionPane.showMessageDialog(null, "Wrong data");
}
}
}
res.close();
prepst.close();
con.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error with connection");
}
}
});
ext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
frame.dispose();
}
});
frame.setVisible(true);
}
public void lol() {
JFrame f = new JFrame("SUCCESS");
f.setSize(200,200);
frame.dispose();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
boolean test(Connection con, String login, String pass) throws SQLException {
int rez = 0;
PreparedStatement st = con.prepareStatement("SELECT COUNT(*) FROM USERS WHERE LOGIN=? AND PASSWORD=?");
st.setString(1, login);
st.setString(2, pass);
ResultSet res = st.executeQuery();
while (res.next()) {
rez = res.getInt(1);
}
st.close();
return rez == 1;
}
public static void main(String[] args) {
new First();
}
}
You're missing a PreparedStatement placeholder character from your SQL, replace
SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?
with
SELECT * FROM USERS WHERE LOGIN=? AND PASSWORD=?
^
If you're getting an Exception, its always best to display the exception content. You could add this to the exception block:
e.printStackTrace();