prepareStatement throwing errors for getPassword - java

I'm brand new to eclipse and I am trying to create a registration interface. As a shell it was working fine i.e. it would take input and display warnings if not input was given, but it wasn't connected to a database. I am now trying to connect it to my database with a prepareStatement but I am reciving an eror for the setString of the some parameters. I tried changing the error with one of the recommendation fixes which was "change type of p1 to 'String'", but nothing changed. How do I use setString for a password?
I know that not every txtField is being asked for in the query, I wanted to try it with a few first before trying to insert all of them.
The 'ConnectDB' connection works as I have it connected in a separate class but it's a simple prepareStatement of only one insert. What am I doing wrong?
package project_files;
import javax.swing.*;
import Connection.ConnectDB;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Arrays;
public class registration_test extends JFrame implements ActionListener
{
Connection con = null;
PreparedStatement pst = null;
JLabel l1, l2, l3, l4, l5, l6, l7, l8;
JTextField txtname, txtid, txtDOB, txtState, txtNum;
JButton btnSubmit, btn2;
JPasswordField p1, p2;
private JLabel Lname;
private JTextField textLname;
public registration_test()
{
setVisible(true);
setSize(700, 700);
getContentPane().setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Registration Form");
l1 = new JLabel("Registration Form");
l1.setForeground(Color.blue);
l1.setFont(new Font("Serif", Font.BOLD, 20));
l2 = new JLabel("First Name:");
l3 = new JLabel("Email-ID:");
l4 = new JLabel("Create Passowrd:");
l5 = new JLabel("Confirm Password:");
l6 = new JLabel("DOB");
l7 = new JLabel("State:");
l8 = new JLabel("Phone No:");
txtname = new JTextField();
txtid = new JTextField();
p1 = new JPasswordField();
p2 = new JPasswordField();
txtDOB = new JTextField();
txtState = new JTextField();
txtNum = new JTextField();
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
PreparedStatement st = ConnectDB.prepareStatement("INSERT INTO userdatabase . users (FirstName, LastName, Email, Password, Phone Number) VALUES ('?','?','?','?'");
st.setString(1, txtname.getText());
st.setString(2, textLname.getText());
st.setString(3, txtid.getText());
st.setString(4, p1.getPassword());
st.setString(5, txtNum.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "REGISTER SUCCESSFULLY");
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
JFrame frmregistration_test = new JFrame("Submit");
if (txtname.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "All fields must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
}
else if (textLname.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "All fields must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
}
else if (txtDOB.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "All fields must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
}
else if (txtNum.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "All fields must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
}
else if (txtState.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "All fields must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
}
else if (txtid.getText().isEmpty())
{
JOptionPane.showMessageDialog(null, "All fields must be filled in", "Login Warning", JOptionPane.WARNING_MESSAGE);
}
else if (p1.getPassword().length == 0 || p2.getPassword().length == 0){
JOptionPane.showMessageDialog(null, "Passwords fields can not be empty.", "Woops", JOptionPane.ERROR_MESSAGE);
}
else if (!Arrays.equals(p1.getPassword(), p2.getPassword())) {
JOptionPane.showMessageDialog(null, "Passwords do not match.", "Woops", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null, "Registered Successfully", "Login Warning", JOptionPane.WARNING_MESSAGE);
}
}});
btn2 = new JButton("Clear");
btnSubmit.addActionListener(this);
btn2.addActionListener(this);
l1.setBounds(100, 30, 400, 30);
l2.setBounds(80, 70, 200, 30);
l3.setBounds(80, 361, 200, 30);
l4.setBounds(80, 150, 200, 30);
l5.setBounds(80, 190, 200, 30);
l6.setBounds(80, 230, 200, 30);
l7.setBounds(80, 270, 200, 30);
l8.setBounds(80, 310, 200, 30);
txtname.setBounds(300, 70, 200, 30);
txtid.setBounds(300, 361, 200, 30);
p1.setBounds(300, 150, 200, 30);
p2.setBounds(300, 190, 200, 30);
txtDOB.setBounds(300, 230, 200, 30);
txtState.setBounds(300, 270, 200, 30);
txtNum.setBounds(300, 310, 200, 30);
btnSubmit.setBounds(50, 402, 100, 30);
btn2.setBounds(168, 402, 100, 30);
getContentPane().add(l1);
getContentPane().add(l2);
getContentPane().add(txtname);
getContentPane().add(l3);
getContentPane().add(txtid);
getContentPane().add(l4);
getContentPane().add(p1);
getContentPane().add(l5);
getContentPane().add(p2);
getContentPane().add(l6);
getContentPane().add(txtDOB);
getContentPane().add(l7);
getContentPane().add(txtState);
getContentPane().add(l8);
getContentPane().add(txtNum);
getContentPane().add(btnSubmit);
getContentPane().add(btn2);
Lname = new JLabel("Last Name");
Lname.setBounds(80, 112, 70, 14);
getContentPane().add(Lname);
textLname = new JTextField();
textLname.setBounds(300, 111, 200, 28);
getContentPane().add(textLname);
textLname.setColumns(10);
}
public static void main(String args[])
{
new registration_test();
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
In case you need to see the connection it is:
package Connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ConnectDB {
//DB Connection variables
static Connection connection = null;
static String databaseName = "";
static String url = "jdbc:mysql://localhost:3306/" +databaseName;
static String username = "root";
static String password = "pass1234";
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
connection = DriverManager.getConnection(url, username, password);
PreparedStatement ps = connection.prepareStatement("INSERT INTO `userdatabase` . `user` (`UserId`, `FirstName`, `LastName`, `Phone Number`, `Email`, `Password`) VALUES ('5', 'Eugene', 'Miller', '586231234', 'Eugene1#gmail.com', 'password');");
int status = ps.executeUpdate();
if (status != 0) {
System.out.println("Datebase was Connected");
System.out.println("Record was Inserted");
}
}
public static PreparedStatement prepareStatement(String string) {
// TODO Auto-generated method stub
return null;
}
}

Some errors I've spoted so far:
Method ConnectDb.prepareStatement should return a non-null, valid PreparedStatement object (as #Abra wisely pointed out). When implementing it, remember to initialize properly the connection object.
Review the SQL statement set in the method prepareStatement: You must put as many placeholders (question marks) in the VALUES clause as columns in the INSERT clause, and they must not be quoted. Also, remember that one column's name shall not include any blanks.

Related

Trying to take data from JFrame and insert into SQLite. Connection works but insertion only inserts blank line. Why?

I am trying to insert some data into my SQLite database with the method "insertSQLB1". However everytime I type something in my TextField it only inserts a blank line into the database. I am still a beginner in Java and thankful for all the advice I can get :)
Code is as follows:
import javax.swing.*;
public class Main {
public static void main(String args[]) {
JFrame frame1 = new JFrame();
frame1.setTitle("Password Saver");
frame1.setSize(600, 600);
frame1.setLocation(800, 200);
frame1.setResizable(false);
frame1.add(new JFrameFunctionality());
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class JFrameFunctionality extends JPanel {
JTextField tf1;
JTextField tf2;
JTextField tf3;
PreparedStatement prepstat = null;
public JFrameFunctionality() {
setLayout(null);
//FIRST PART - Create a JLabel to let the user know what to enter in
first TextField
JLabel label1 = new JLabel("Neues Passwort:");
label1.setBounds(50, 70, 150, 40);
add(label1);
//FIRST PART - Create first TextField to enter password
tf1 = new JTextField();
tf1.setBounds(50, 100, 150, 40);
add(tf1);
repaint();
//FIRST PART - Create second TextField to enter name of the program
tf2 = new JTextField();
tf2.setBounds(50, 140, 150, 40);
add(tf2);
repaint();
//FIRST PART - Create first button to add new password
JButton button1 = new JButton("Add new Password");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
codeforButtons cfBobj1 = new codeforButtons();
cfBobj1.insertSQLB1();
}
});
button1.setBounds(200, 100, 150, 30);
add(button1);
//SECOND PART - Create a JLabel to let the user know where to enter when changing password
JLabel label2 = new JLabel("Enter new Password for change:");
label2.setBounds(50, 170, 200, 40);
add(label2);
//SECOND PART//Create second TextField to enter a new Password when changing Password
tf3 = new JTextField();
tf3.setBounds(50, 200, 150, 40);
add(tf3);
//SECOND PART//Create second button to take the changed Password and put it where the old password was
JButton button3 = new JButton("Change Password");
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {}
});
button3.setBounds(200, 200, 150, 30);
add(button3);
//THIRD PART//Create third button to display a existing password
JButton button2 = new JButton("Display Password");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//DatabaseConnection con2 = new DatabaseConnection ();
//con2.listPasswords();
}
});
button2.setBounds(200, 250, 150, 30);
add(button2);
} //Konstruktur Ende
public String retrieveTextTF1() { //Retrieve Text from TextField 1
return tf2.getText();
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class codeforButtons extends JFrameFunctionality {
Connection con1 = null;
Connection con2 = null;
PreparedStatement stat1 = null;
Statement stat2 = null;
ResultSet rs = null;
public void getConnection() { //Establishes a connection to the database "passwords"
try {
Class.forName("org.sqlite.JDBC");
con1 =
DriverManager.getConnection("JDBC:sqlite:PasswordDatabase.sqlite");
System.out.println("Connection established...");
} catch (Exception e) {
System.out.println("Error: " + " " + e.getMessage());
}
}
public void insertSQLB1() { //Inserts the application name into the database *not working, inserts only a blank row*
try {
getConnection();
String query = "INSERT INTO passwords (Anwendung) VALUES (?)";
PreparedStatement stat1 = con1.prepareStatement(query);
stat1.setString(1, tf2.getText());
stat1.execute();
JOptionPane.showMessageDialog(null, "Data saved!");
con1.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
public void listPasswords() { //Gibt alle Passwörter aus der Datenbank aus und unterbricht dann die Verbindung zur DB
try {
getConnection();
this.stat2 = con2.createStatement();
ResultSet rs = stat1.executeQuery("SELECT * FROM passwords");
while (rs.next()) {
String password = rs.getString("Passwort");
String program = rs.getString("Anwendung");
System.out.println("Passwort: " + password + " " + "Anwendung: " + program);
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
The problem is that you have your codeforButtons class extending JFrameFunctionality so it is getting its own instance of tf2 which is hiding the instance that is used in the display. (You are creating 2 instance of tf2)
Move the codeforButtons to be a nested inner class of JFrameFunctionality and then remove the extends JFrameFunctionality from codeforButtons and you will have the correct scope to read the tf2 variable.
See below:
public class JFrameFunctionality extends JPanel {
JTextField tf1;
JTextField tf2;
JTextField tf3;
PreparedStatement prepstat = null;
public JFrameFunctionality() {
setLayout(null);
// FIRST PART - Create a JLabel to let the user know what to enter in
// first TextField
JLabel label1 = new JLabel("Neues Passwort:");
label1.setBounds(50, 70, 150, 40);
add(label1);
// FIRST PART - Create first TextField to enter password
tf1 = new JTextField();
tf1.setBounds(50, 100, 150, 40);
add(tf1);
// repaint();
// FIRST PART - Create second TextField to enter name of the program
tf2 = new JTextField();
tf2.setText("test");
tf2.setBounds(50, 140, 150, 40);
add(tf2);
// repaint();
// FIRST PART - Create first button to add new password
JButton button1 = new JButton("Add new Password");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("::" + tf2.getText());
codeforButtons cfBobj1 = new codeforButtons();
cfBobj1.insertSQLB1();
}
});
button1.setBounds(200, 100, 150, 30);
add(button1);
// SECOND PART - Create a JLabel to let the user know where to enter when changing password
JLabel label2 = new JLabel("Enter new Password for change:");
label2.setBounds(50, 170, 200, 40);
add(label2);
// SECOND PART//Create second TextField to enter a new Password when changing Password
tf3 = new JTextField();
tf3.setBounds(50, 200, 150, 40);
add(tf3);
// SECOND PART//Create second button to take the changed Password and put it where the old password was
JButton button3 = new JButton("Change Password");
button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
button3.setBounds(200, 200, 150, 30);
add(button3);
// THIRD PART//Create third button to display a existing password
JButton button2 = new JButton("Display Password");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// DatabaseConnection con2 = new DatabaseConnection ();
// con2.listPasswords();
}
});
button2.setBounds(200, 250, 150, 30);
add(button2);
} // Konstruktur Ende
public static void main(String args[]) {
JFrame frame1 = new JFrame();
frame1.setTitle("Password Saver");
frame1.setSize(600, 600);
frame1.setLocation(800, 200);
frame1.setResizable(false);
frame1.add(new JFrameFunctionality());
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
public class codeforButtons {
Connection con1 = null;
Connection con2 = null;
PreparedStatement stat1 = null;
Statement stat2 = null;
ResultSet rs = null;
public void getConnection() { // Establishes a connection to the database "passwords"
try {
Class.forName("org.sqlite.JDBC");
con1 = DriverManager.getConnection("JDBC:sqlite:PasswordDatabase.sqlite");
System.out.println("Connection established...");
} catch (Exception e) {
System.out.println("Error: " + " " + e.getMessage());
}
}
public void insertSQLB1() { // Inserts the application name into the database *not working, inserts only a blank
// row*
try {
getConnection();
String query = "INSERT INTO passwords (Anwendung) VALUES (?)";
PreparedStatement stat1 = con1.prepareStatement(query);
stat1.setString(1, tf2.getText());
stat1.execute();
JOptionPane.showMessageDialog(null, "Data saved!");
con1.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
public void listPasswords() { // Gibt alle Passwörter aus der Datenbank aus und unterbricht dann die Verbindung
// zur
// DB
try {
getConnection();
this.stat2 = con2.createStatement();
ResultSet rs = stat1.executeQuery("SELECT * FROM passwords");
while (rs.next()) {
String password = rs.getString("Passwort");
String program = rs.getString("Anwendung");
System.out.println("Passwort: " + password + " " + "Anwendung: " + program);
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
===
Or alternativly, remove the extends JFrameFunctionality from codeforButtons then change insertSQLB1 to accept a String as a parameter passed in.
public void insertSQLB1(String value) { // Inserts the application name into the database *not working, inserts only a blank
// row*
try {
getConnection();
String query = "INSERT INTO passwords (Anwendung) VALUES (?)";
PreparedStatement stat1 = con1.prepareStatement(query);
stat1.setString(1, value);
stat1.execute();
JOptionPane.showMessageDialog(null, "Data saved!");
con1.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
Then change the caller to
cfBobj1.insertSQLB1(tf2.getText());
This way you are passing the value into the data management class and would achieve a better split between the interface layer and the data management layer.

having trouble with inserting data to a database

When I enter data to a database using the sample code below, the line System.out.println("Insertion complete") is shown on the console. When I go to the database, I find that the stored data is a blank.
I think the problem could be my sqlquery, but I don't see any problem with it.
Here is an example of my code:
public class SignUpFrame extends JFrame {
public SignUpFrame() {
super("SIGN UP");
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
setResizable(false);
setLocation(500, 250);
getContentPane().setBackground(Color.WHITE);
ImageIcon FrameIcon = new ImageIcon("images/signup.png");
JLabel frameicon = new JLabel(FrameIcon);
frameicon.setBounds(150, 0, 100, 100);
add(frameicon);
JLabel firstNamelbl,LastNameLbl,EmailAddressLbl,PasswordLbl,ConfirmPasswordLbl;
JTextField firstNametxt,LastNametxt,EmailAddresstxt;
JPasswordField passwordtxt,ConfirmPasswordtxt;
JButton OKbtn;
JButton CANCELbtn;
firstNamelbl = new JLabel("FIRST NAME:");
firstNametxt = new JTextField();
firstNametxt.setBounds(150, 110, 200, 20);
firstNamelbl.setBounds(50, 110, 100, 20);
LastNameLbl = new JLabel("USERNAME:");
LastNametxt = new JTextField();
LastNametxt.setBounds(150, 140, 200, 20);
LastNameLbl.setBounds(50,140, 100, 20);
EmailAddressLbl = new JLabel("EMAIL ADDRESS:");
EmailAddresstxt = new JTextField();
EmailAddresstxt.setBounds(150, 170, 200, 20);
EmailAddressLbl.setBounds(50, 170, 150, 20);
PasswordLbl = new JLabel("PASSWORD:");
passwordtxt = new JPasswordField();
passwordtxt.setBounds(150, 200, 200, 20);
PasswordLbl.setBounds(50, 200, 150, 20);
ConfirmPasswordLbl = new JLabel("CONFIRM PASSWORD:");
ConfirmPasswordtxt = new JPasswordField();
ConfirmPasswordtxt.setBounds(200, 230, 150, 20);
ConfirmPasswordLbl.setBounds(50, 230, 150, 20);
add(firstNamelbl);
add(firstNametxt);
add(LastNameLbl);
add(LastNametxt);
add(EmailAddressLbl);
add(EmailAddresstxt);
add(PasswordLbl);
add(passwordtxt);
add(ConfirmPasswordLbl);
add(ConfirmPasswordtxt);
OKbtn = new JButton("OK");
OKbtn.setBounds(100, 270, 50, 20);
add(OKbtn);
char [] pass = passwordtxt.getPassword();
String passWord = new String(pass);
String FIRSTNAME,USERNAME,EMAIL,PASSWORD;
FIRSTNAME = firstNametxt.getText().toString();
USERNAME =LastNametxt.getText().toString();
EMAIL = EmailAddresstxt.getText().toString();
PASSWORD = passWord;
OKbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String url = "jdbc:mysql://localhost:3306/System";
String user = "root";
String password = "";
Connection con;
try {
con = DriverManager.getConnection(url, user, password);
Statement statement = con.createStatement();
String sqlquery = "insert into signUp_tb "+
"(FirstName,UserName,Email,Password) values ('"+FIRSTNAME+"','"+USERNAME+"','"+EMAIL+"','"+PASSWORD+"')";
statement.executeUpdate(sqlquery);
System.out.println("Insertion complete");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
CANCELbtn = new JButton("CANCEL");
CANCELbtn.setBounds(170, 270, 100, 20);
add(CANCELbtn);
CANCELbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
});
}
}
You need to initialize your FIRSTNAME, USERNAME etc in ActionListener for OK button. You had initialized those Strings when there was no input data, that's why everything was blank. You want to get JTextFields values when user presses button. Not before.
Tested on SQLite.
OKbtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
char [] pass = passwordTxt.getPassword();
String PASSWORD = new String(pass);
String FIRSTNAME,USERNAME,EMAIL;
FIRSTNAME = firstNameTxt.getText();
USERNAME = lastNameTxt.getText();
EMAIL = emailAddressTxt.getText();
String url = "jdbc:mysql://localhost:3306/System";
String user = "root";
String password = "";
Connection con;
try {
con = DriverManager.getConnection(url, user, password);
Statement statement = con.createStatement();
String sqlquery = "insert into signUp_tb "+
"(FirstName,UserName,Email,Password) values ('"+FIRSTNAME+"','"+USERNAME+"','"+EMAIL+"','"+PASSWORD+"')";
statement.executeUpdate(sqlquery);
System.out.println("Insertion complete");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
And setVisible(true) should be the last thing you do. Should look like:
SwingUtilities.invokeLater(() -> {
this.setVisible(true);
});
So you will launch it from EDT.
Edit: about setLayout(null) - Try those A Visual Guide to Layout Managers .
Although it is possible to do without a layout manager, you should use
a layout manager if at all possible. A layout manager makes it easier
to adjust to look-and-feel-dependent component appearances, to
different font sizes, to a container's changing size, and to different
locales. Layout managers also can be reused easily by other
containers, as well as other programs.
From Doing Without a Layout Manager (Absolute positioning)

ORA-00927: missing equal sign java eclipse

When I try to run a code I got an error message "ORA-00927: missing equal sign" which can not detect it in the code and can not fix it. I mean that error is in the UPDATE method but i'm not sure.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;strong text
import javax.swing.border.EmptyBorder;
import net.proteanit.*;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
public class Korisnici extends JFrame {
private JPanel contentPane;
private JTable table;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Korisnici frame = new Korisnici();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
protected ResultSet rs;
private JTextField textFieldPhoneNumber;
private JTextField textFieldName;
private JTextField textFieldEmail;
private JTextField textFieldID;
public Korisnici() {
connection = sqlConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 777, 512);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnLoadTable = new JButton("Load \"Korisnici\" table");
btnLoadTable.setFont(new Font("Tahoma", Font.BOLD, 14));
btnLoadTable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "SELECT * FROM KORISNICI";
PreparedStatement pst= connection.prepareStatement(query);
ResultSet ps = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(ps));
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnLoadTable.setBounds(411, 11, 211, 50);
contentPane.add(btnLoadTable);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(305, 83, 446, 311);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JLabel lblId = new JLabel("ID");
lblId.setFont(new Font("Tahoma", Font.BOLD, 14));
lblId.setBounds(10, 83, 115, 60);
contentPane.add(lblId);
JLabel lblEmail = new JLabel("Email");
lblEmail.setFont(new Font("Tahoma", Font.BOLD, 14));
lblEmail.setBounds(10, 154, 115, 60);
contentPane.add(lblEmail);
JLabel lblName = new JLabel("Name");
lblName.setFont(new Font("Tahoma", Font.BOLD, 14));
lblName.setBounds(10, 225, 115, 60);
contentPane.add(lblName);
JLabel lblPhonenumber = new JLabel("Phone number");
lblPhonenumber.setFont(new Font("Tahoma", Font.BOLD, 14));
lblPhonenumber.setBounds(10, 296, 120, 60);
contentPane.add(lblPhonenumber);
textFieldPhoneNumber = new JTextField();
textFieldPhoneNumber.setBounds(135, 313, 155, 30);
contentPane.add(textFieldPhoneNumber);
textFieldPhoneNumber.setColumns(10);
textFieldName = new JTextField();
textFieldName.setBounds(135, 242, 155, 30);
contentPane.add(textFieldName);
textFieldName.setColumns(10);
textFieldEmail = new JTextField();
textFieldEmail.setBounds(135, 171, 155, 30);
contentPane.add(textFieldEmail);
textFieldEmail.setColumns(10);
textFieldID = new JTextField();
textFieldID.setBounds(135, 100, 155, 30);
contentPane.add(textFieldID);
textFieldID.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "INSERT INTO korisnici (ID, EMAIL, NAME, PHONE_NUMBER) values (?, ?, ?, ?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textFieldID.getText());
pst.setString(2, textFieldEmail.getText());
pst.setString(3, textFieldName.getText());
pst.setString(4, textFieldPhoneNumber.getText());
ResultSet rs = pst.executeQuery();
JOptionPane.showMessageDialog(null, "Data Saved");
pst.close();
rs.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnSave.setFont(new Font("Tahoma", Font.BOLD, 14));
btnSave.setBounds(10, 400, 90, 40);
contentPane.add(btnSave);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "UPDATE korisnici SET ID='"+textFieldID.getText()+"' ,email='"+textFieldEmail.getText()+"' ,name='"+textFieldName.getText()+"' ,Phone number='"+textFieldPhoneNumber.getText()+"' ";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data Updated");
pst.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 14));
btnUpdate.setBounds(110, 400, 90, 40);
contentPane.add(btnUpdate);
}
}
The update:
String query = "UPDATE korisnici SET ID='"+textFieldID.getText()
+"' ,email='"+textFieldEmail.getText()+"',name='"+textFieldName.getText()
+"' ,Phone number='"+textFieldPhoneNumber.getText()+"' ";
constains this snippet:
.... ,Phone number='"+ .....
In Oracle nonquoted identifiers cannot contain spaces, see this:
https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements008.htm
Nonquoted identifiers can contain only alphanumeric characters from
your database character set and the underscore (_), dollar sign ($),
and pound sign (#). Database links can also contain periods (.) and
"at" signs (#). Oracle strongly discourages you from using $ and # in
nonquoted identifiers.
Quoted identifiers can contain any characters and punctuations marks
as well as spaces. However, neither quoted nor nonquoted identifiers
can contain double quotation marks or the null character (\0).
In other words: Phone number is treated as a column named Phone, and Oracle expects = after a column name in the update statement, but it gets number, then throws the error.

retrieve mysql data when i change combobox item in java

I use the following code to retrieve data from msysql database to a JComboBox. It was working properly. My problem is when I execute this code, if I click jCombobox, only one item is shown and it displays the related data from database.. it is not getting all the ids from database to Combobox, so that i can select a particular id and display related data.
package Swings;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.*;
import javax.swing.*;
class Frame3 extends JFrame implements ActionListener,ItemListener
{
private JFrame frame;
JPanel panel=new JPanel();
JButton btn1,btn2,btn3;
JLabel l1, l2, l3, l4, l5, l6, l7;
private JComboBox SummonIdbox;
private JTextField txtcarLicenceNo;
private JTextField txtamount;
private JTextField txtdateFined;
private JTextField txtlocation;
private JTextField txtofficerInCharge;
String dbURL = "jdbc:mysql://localhost:3306/cpss";
String username ="root";
String password = "root";
Connection c = null;
Statement st = null;
ResultSet rs = null;
Frame3()
{
setVisible(true);
setSize(700, 700);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("CPSS Application");
l1 = new JLabel("Update Summon Details");
l1.setForeground(Color.blue);
l1.setFont(new Font("Serif", Font.BOLD, 20));
l2 = new JLabel("SummonId");
l3 = new JLabel("Car LicenceNo:");
l4 = new JLabel("Amount");
l5 = new JLabel("DateFined");
l6 = new JLabel("Location");
l7 = new JLabel("Officer Incharge");
SummonIdbox = new JComboBox();
txtcarLicenceNo = new JTextField();
txtamount = new JTextField();
txtdateFined = new JTextField();
txtlocation = new JTextField();
txtofficerInCharge=new JTextField();
btn1 = new JButton("Update");
btn2 = new JButton("Clear");
btn3= new JButton("Home");
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
SummonIdbox.addItemListener(this);
l1.setBounds(500, 30, 400, 30);
l2.setBounds(400, 70, 200, 30);
l3.setBounds(400, 110, 200, 30);
l4.setBounds(400, 150, 200, 30);
l5.setBounds(400, 190, 200, 30);
l6.setBounds(400, 230, 200, 30);
l7.setBounds(400, 270, 200, 30);
SummonIdbox.setBounds(500, 70, 200, 30);
txtcarLicenceNo.setBounds(500, 110, 200, 30);
txtamount.setBounds(500, 150, 200, 30);
txtdateFined.setBounds(500, 190, 200, 30);
txtlocation.setBounds(500, 230, 200, 30);
txtofficerInCharge.setBounds(500, 270, 200, 30);
btn1.setBounds(450, 350, 100, 30);
btn2.setBounds(600, 350, 100, 30);
btn3.setBounds(750, 350, 100, 30);
add(l1);
add(l2);
add(SummonIdbox);
add(l3);
add(txtcarLicenceNo);
add(l4);
add(txtamount);
add(l5);
add(txtdateFined);
add(l6);
add(txtlocation);
add(l7);
add(txtofficerInCharge);
add(btn1);
add(btn2);
add(btn3);
add_summonid(SummonIdbox);
}
#Override
public void actionPerformed(ActionEvent ae ) {
if(ae.getSource() == btn2)
{
txtcarLicenceNo.setText("");
txtamount.setText("");
txtdateFined.setText("");
txtlocation.setText("");
txtofficerInCharge.setText("");
}
else if (ae.getSource() == btn3)
{
SwingMenu s=new SwingMenu();
s.setSize(800,800);
s.setVisible(true);
}
}
void add_summonid(JComboBox SummonIdbox)
{
try
{
//Class.forName("com.mysql.jdbc.Driver");
//System.out.println("Driver is loaded");
c = DriverManager.getConnection(dbURL, username, password);
System.out.println("Connection created");
st=c.createStatement();
rs=st.executeQuery("select Summonid from summon");
while(rs.next())
SummonIdbox.addItem(rs.getInt(1));
// c.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
#Override
public void itemStateChanged(ItemEvent ie) {
int item= (Integer) SummonIdbox.getSelectedItem();
System.out.println(item);
String sql="select carLicenceNo,amount,dateFined,location,officerIncharge from summon where summonId='"+item+"'";
try {
PreparedStatement pst = c.prepareStatement(sql);
//pst.setInt(1,item);
rs=pst.executeQuery();
while(rs.next())
{
txtcarLicenceNo.setText(rs.getString(1));
txtamount.setText(String.valueOf((rs.getDouble(2))));
txtdateFined.setText(rs.getString(3));
txtlocation.setText(rs.getString(4));
txtofficerInCharge.setText(rs.getString(5));
/*System.out.println(rs.getString(1));
System.out.println(rs.getDouble(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));*/
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Java Exception nullpointerexception error

What is causing the null exception here? I am simply unable to see it.. please second set of eyes would help this beginner java student..This application basically captures 5 pieces of info about a game team and insert into mySQL database.
The error is as below:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at InsertTeamInfo.insertRecord(InsertTeamInfo.java:130) at InsertTeamInfo.access$100(InsertTeamInfo.java:11)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class InsertTeamInfo extends JFrame{
private String sql;
private Connection con;
private Statement stat;
private JButton btnSave;
private JTextField txtTeam;
private JTextField txtCity;
private JTextField txtYear;
private JTextField txtLoserTeam;
private JTextField txtLoserCity;
private JLabel lblTeam;
private JLabel lblCity;
private JLabel lblYear;
private JLabel lblLoserTeam;
private JLabel lblLoserCity;
public InsertTeamInfo(){
super("Favorite Team");
btnSave = new JButton("Save");
txtTeam = new JTextField("");
txtCity = new JTextField("");
txtYear = new JTextField("");
txtLoserTeam = new JTextField("");
txtLoserCity = new JTextField("");
lblTeam = new JLabel("Team");
lblCity = new JLabel("City");
lblYear = new JLabel("Year Played");
lblLoserTeam = new JLabel("Loser Team");
lblLoserCity = new JLabel("Loser City");
txtYear.setEditable(true);
txtLoserTeam.setEditable(true);
txtLoserCity.setEditable(true);
txtTeam.setEditable(true);
txtCity.setEditable(true);
}
public void launchJFrame(){
//width - height
setSize(500, 300);
getContentPane().setLayout(null);
getContentPane().setBackground(Color.white);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
getContentPane().add(btnSave);
getContentPane().add(txtTeam);
getContentPane().add(txtCity);
getContentPane().add(txtYear);
getContentPane().add(txtLoserTeam);
getContentPane().add(txtLoserCity);
getContentPane().add(lblTeam);
getContentPane().add(lblCity);
getContentPane().add(lblYear);
getContentPane().add(lblLoserTeam);
getContentPane().add(lblLoserCity);
lblTeam.setBounds(new Rectangle(65,20,100,30));
lblCity.setBounds(new Rectangle(65,55,100,30));
lblYear.setBounds(new Rectangle(65, 85, 100, 30));
lblLoserTeam.setBounds(new Rectangle(65, 115, 100, 30));
lblLoserCity.setBounds(new Rectangle(65, 145, 100, 30));
txtTeam.setBounds(new Rectangle(210, 20, 150, 30));
txtCity.setBounds(new Rectangle(210, 54, 150, 30));
txtYear.setBounds(new Rectangle(210, 86, 150, 30));
txtLoserTeam.setBounds(new Rectangle(210, 119, 150, 30));
txtLoserCity.setBounds(new Rectangle(210, 150, 150, 30));
btnSave.setBounds(new Rectangle(65, 190, 90, 30));
setVisible(true);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
shutDown();
}
});
btnSave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){ //Handle Save button click event
insertRecord();
}
});
}
private void insertRecord(){
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/week5", "root","Saras231");
}
catch(Exception ex){
JOptionPane.showMessageDialog( null, "Error connection to database.");
System.exit(0);
}
try {
sql = "INSERT INTO Wins_S001 (Team, City, Year_T, LoserTeam, LoserCity) VALUES (?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = con.prepareStatement(sql);
preparedStatement.setString(1, txtTeam.getText());
preparedStatement.setString(2, txtCity.getText());
preparedStatement.setString(3, txtYear.getText());
preparedStatement.setString(4, txtLoserTeam.getText());
preparedStatement.setString(5, txtLoserCity.getText());
preparedStatement.executeUpdate();
JOptionPane.showMessageDialog( null, "Data Inserted Successfully");
}
catch(SQLException ex){
ex.printStackTrace();
JOptionPane.showMessageDialog( null, "Data Insert failed.");
}
try{
stat.close();
con.close();
}
catch(SQLException ex){
JOptionPane.showMessageDialog( null, "All active connection closed to the database.");
}
}
private void shutDown(){
int returnVal = JOptionPane.showConfirmDialog(this, "Are you sure you want to quit?");
if(returnVal == JOptionPane.YES_OPTION){
System.exit(0);
}
}
public static void main(String[] args){
InsertTeamInfo gui = new InsertTeamInfo();
gui.launchJFrame();
}
}
Remove the stat instance variable. Remove the con instance variable. Remove the sql instance variable. They should all be local variables (and that's probably the cause of your exception: you're closing stat instead of closing preparedStatement. The line number in the stack trace should confirm it).
Also, make sure these are closed in a finally block, to be absolutely sure that they're closed. And beware: if closing the prepared statement throws an exception, the connection won't be closed.

Categories