Java Exception nullpointerexception error - java

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.

Related

How can I avoid sending hardcoded values to mySQL database

In my project I've assembled a basic password book, the project is designed to send user information over to a mySQL database after the "Save Information" button has been clicked. It works fine when the String values are hardcoded, but when I try to use any kind of String variable or the toString() method I start getting errors. Does anyone know the correct way to send UN-hardcoded values to mySQL?
import javax.swing.*;
//import java.io.*;
//import java.lang.Thread.State;
import java.awt.event.*;
import java.sql.*;
public class PasswordBook implements ActionListener
{
private static JLabel websiteLabel;
private static JTextField websiteText;
private static JLabel userLabel;
private static JTextField userText;
private static JLabel passLabel;
private static JTextField passText;
private static JLabel emailLabel;
private static JTextField emailText;
private static JButton button;
private static JButton clearButton;
private static JLabel success;
//private static String websiteToString; (values I tried)
//private static String userToString;
//private static String emailToString;
//private static String passToString;
public static void main (String[]args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(400,350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null); // rows columns
websiteLabel = new JLabel("Website"); //1st
websiteLabel.setBounds(10, 20, 80, 25);
panel.add(websiteLabel);
websiteText = new JTextField(); //1st
websiteText.setBounds(100, 20, 165, 25);
panel.add(websiteText);
//websiteToString = websiteText.toString();
userLabel = new JLabel("Username"); //2nd
userLabel.setBounds(10, 60, 80 ,25);
panel.add(userLabel);
userText = new JTextField(20); // 2nd
userText.setBounds(100, 60, 165, 25);
panel.add(userText);
//userToString = userText.toString();
emailLabel = new JLabel("Email"); //3rd
emailLabel.setBounds(10, 100, 80 ,25);
panel.add(emailLabel);
emailText = new JTextField(); //2nd
emailText.setBounds(100, 100, 165, 25);
panel.add(emailText);
//emailToString = emailText.toString();
passLabel = new JLabel("Password"); //4th
passLabel.setBounds(10, 140, 80, 25);
panel.add(passLabel);
passText = new JTextField(); // 4th
passText.setBounds(100, 140, 165, 25);
panel.add(passText);
//passToString = passText.toString();
button = new JButton("Save Information");
button.setBounds(10, 180, 150 ,25);
button.addActionListener(new PasswordBook()); // action listener to button
panel.add(button);
clearButton = new JButton("Clear");
clearButton.setBounds(180, 180, 150, 25);
// CLEARS THE TEXT FIELDS WHEN PRESSED
clearButton.addActionListener(new ActionListener() {
#Override // Override allows function to perfrom independently of the parent class
public void actionPerformed(ActionEvent event)
{
websiteText.setText("");
userText.setText("");
emailText.setText("");
passText.setText("");
success.setText("");
}
});
panel.add(clearButton);
success = new JLabel("");
success.setBounds(10, 220, 300, 25);
panel.add(success);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/passwordbook", "root", "password");
//Statement myStatement = myConn.createStatement();
String sq1 = "INSERT into website_and_user_info"
+ " (Website, Username, Email, Password)"
+ " values (?, ?, ?, ?)";
PreparedStatement statement = myConn.prepareStatement(sq1);
statement.setString(1, websiteText.toString()); // These values work when hardcoded
statement.setString(2, userText.toString());
statement.setString(3, emailText.toString());
statement.setString(4, passText.toString());
statement.executeUpdate();
System.out.println("insert complete");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If I read it right, passText is a Textfild (advice use Hungarian notation, makes code easier to read) to get the text you need .gettext(). Like prepared preparedStatement.setString(int, passText.getText()); that should do the trick. But you need to get text before clearing the fields. You Code seems to first clear and you use .setTxt in the statement. If iam wrong I'm sry, atm.i just have my phone to browse.

prepareStatement throwing errors for getPassword

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.

JFrame doesn't load for multiple clients

I am not able to load JFrame for multiple clients whereas it works fine for a single client. I am able to perform all the operations on a single client. The frame becomes visible but the contents are not.
Do I need to add something extra? Am I making the correct connections?I am running it on my local machine.
Can I run multiple instances on the same machine?
Server :
public class ServerThread extends Thread{
public static void main(String[] args) throws IOException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(4518);
while(true){
Socket clientSocket = serverSocket.accept();
Thread window=new Frame1();
window.start();
}
} catch (Exception e) {
e.printStackTrace();
}
Client:
public class Client extends JFrame{
public static void main(String arg[]){
String hostName="localhost";
int portNumber=4518;
try{
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
}
JFrame:
public class Frame1 extends Thread{
static JFrame frame;
private static JTextField textField;
private static JPasswordField passwordField;
static Connection conn = null;
static PreparedStatement pst = null;
static ResultSet rs = null;
public Frame1() {
System.out.println("hello");
initialize();
}
private static void initialize() {
frame = new JFrame();
frame.setVisible(true);
frame.setTitle("Course Registration- Spring 2017");
frame.getContentPane().setBackground(new Color(204, 204, 255));
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Sign in");
btnNewButton.setBackground(new Color(204, 102, 153));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
conn = DBConnect.DBConnect();
String sql = "Select * from users where username =? and password=?";
try{
String userName=textField.getText();
String password=passwordField.getText();
pst = conn.prepareStatement(sql);
pst.setString(1, userName);
pst.setString(2, password);
rs = pst.executeQuery();
if(userName.equals("admin") && password.equals("admin")){
ServerSideViews s = new ServerSideViews();
s.setVisible(true);
s.setUserName(userName);
s.setFrameLogin(frame);
System.out.println(userName);
frame.setVisible(false);
}
else if(rs.next() && !(userName.equals("admin"))){
JOptionPane.showMessageDialog(null, "Welcome " + textField.getText() );
CourseRegistration c = new CourseRegistration();
c.setVisible(true);
c.setFrameLogin(frame);
frame.setVisible(false);
String sql1 = "Select major from users where username=?;";
System.out.println(sql1);
pst = conn.prepareStatement(sql1);
pst.setString(1, userName);
rs = pst.executeQuery();
String major="";
while(rs.next())
{
major=rs.getString("major");
}
c.setUserName(userName);
c.comboBox.setSelectedItem(major);
c.comboBox.disable();
}
else{
JOptionPane.showMessageDialog(null, "Invalid user name or password");
}
}catch(Exception e1){
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(157, 182, 117, 29);
frame.getContentPane().add(btnNewButton);
JLabel lblUserName = new JLabel("User Name");
lblUserName.setBounds(76, 96, 86, 16);
frame.getContentPane().add(lblUserName);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(86, 129, 61, 16);
frame.getContentPane().add(lblPassword);
textField = new JTextField();
textField.setBounds(157, 91, 130, 26);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton_1 = new JButton("Register");
btnNewButton_1.setBackground(new Color(51, 102, 204));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UserRegistration reg = new UserRegistration();
reg.setVisible(true);
reg.setFrameLogin(frame);
frame.setVisible(false);
}
});
btnNewButton_1.setBounds(157, 225, 117, 29);
frame.getContentPane().add(btnNewButton_1);
passwordField = new JPasswordField();
passwordField.setBounds(157, 124, 130, 26);
frame.getContentPane().add(passwordField);
JLabel lblNewLabel = new JLabel("Course Registration - Spring 2017");
lblNewLabel.setBounds(109, 24, 241, 16);
frame.getContentPane().add(lblNewLabel);
}
}
Don't start a task that blocks on the Event Dispatch Thread (EDT). The GUI won't be able to respond to events.
So don't start the ServerSocket from the SwingUtilities.invokeLater(..).
Instead you need to use a separate Thread for the ServerSocket.
Read the section from the Swing tutorial on Concurrency for more information and examples.

How to save Data to mysql [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
I ve been working on a phonebook program on eclipse java
but and idk how to save information from a textfield to mysql and then be able use it in search, such as writing the name and finding all the info of the specific contact
I also want to save it to my sql
thats my code:
public class Phone {
private JFrame frame;
private JTextField firstfield;
private JTextField phonefield;
private JTextField emailfield;
private JTextField lastfield;
private JPanel MainScreen;
private JPanel newcontact;
private JPanel searchscreen;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Phone window = new Phone();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Phone() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel MainScreen = new JPanel();
frame.getContentPane().add(MainScreen, "name_6058038854379");
MainScreen.setLayout(null);
MainScreen.setVisible(true);
final JPanel newcontact = new JPanel();
newcontact.setLayout(null);
frame.getContentPane().add(newcontact, "name_791613670731");
newcontact.setVisible(false);
final JPanel searchscreen = new JPanel();
frame.getContentPane().add(searchscreen, "name_6068807854350");
searchscreen.setVisible(false);
JButton newrecord = new JButton("New Record");
newrecord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newcontact.setVisible(true);
MainScreen.setVisible(false);
}
});
newrecord.setBounds(63, 99, 116, 52);
MainScreen.add(newrecord);
JButton Search = new JButton("Search");
Search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchscreen.setVisible(true);
newcontact.setVisible(false);
}
});
Search.setBounds(243, 99, 102, 52);
MainScreen.add(Search);
JLabel myphonebook = new JLabel(" My Phonebook");
myphonebook.setBounds(162, 44, 102, 14);
MainScreen.add(myphonebook);
JLabel first = new JLabel("First Name:");
first.setBounds(118, 83, 66, 14);
newcontact.add(first);
JLabel last = new JLabel("Last Name:");
last.setBounds(118, 108, 66, 14);
newcontact.add(last);
JLabel Phone = new JLabel("Phone:");
Phone.setBounds(118, 143, 66, 14);
newcontact.add(Phone);
JLabel Emailadress = new JLabel("Email Adress:");
Emailadress.setBounds(118, 180, 66, 14);
newcontact.add(Emailadress);
firstfield = new JTextField();
firstfield.setColumns(10);
firstfield.setBounds(220, 80, 86, 20);
newcontact.add(firstfield);
lastfield = new JTextField();
lastfield.setColumns(10);
lastfield.setBounds(220, 108, 86, 20);
newcontact.add(lastfield);
phonefield = new JTextField();
phonefield.setColumns(10);
phonefield.setBounds(220, 140, 86, 20);
newcontact.add(phonefield);
emailfield = new JTextField();
emailfield.setColumns(10);
emailfield.setBounds(220, 177, 86, 20);
newcontact.add(emailfield);
JLabel lblNewContact = new JLabel("New Contact");
lblNewContact.setBounds(166, 30, 86, 14);
newcontact.add(lblNewContact);
JButton Save = new JButton("Save");
Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String firstname=firstfield.getText();
String lastname=lastfield.getText();
String phonenumber=phonefield.getText();
String emailadress=emailfield.getText();
}
});
Save.setBounds(81, 232, 89, 23);
newcontact.add(Save);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newcontact.setVisible(false);
MainScreen.setVisible(true);
}
});
cancel.setBounds(283, 232, 89, 23);
newcontact.add(cancel);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_6081212161880");
}
}
Write this into your savecommand. You should only create a database an table and change the uppercased words.
try
{
// create a mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://LOCATION/DATABASE";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into TABLE (first_name, last_name, phone_number, email_adress)"
+ " values (?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, firstname);
preparedStmt.setString (2, lastname);
preparedStmt.setString (3, phonenumber);
preparedStmt.setString (4, emailadress);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}

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.

Categories