Exception during connection to JDBC MySQL - java

Good Afternoon: I'm a chemistry teacher from Spain. I am not an experimented programmer, but I decided to create a small program to help my students with my subject. I am creating this small program in Java where I'm trying to connect with a database in order to receive its information through the Atomic Number. Actually, I also want to do it through the other parameters, but I'm not shure about how to do it. The thing is that it bounces the exception or it doesn't connect properly to the database. I attatch the full code and a screenshot of my database (By the way, when I try to upload data to the database it works.):
package chemInterface;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class Oxidaciones extends JFrame {
private JPanel contentPane;
private JPasswordField pass;
private JTextField smb;
private JTextField elm;
private JTextField ox;
private JTextField nat;
private JTextField mat;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Oxidaciones frame = new Oxidaciones();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Oxidaciones() {
setFont(new Font("Courier Prime", Font.PLAIN, 12));
setTitle("Interface");
setForeground(Color.BLUE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setForeground(Color.BLUE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSmbolo = new JLabel("Smb");
lblSmbolo.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblSmbolo.setBounds(10, 30, 67, 14);
contentPane.add(lblSmbolo);
JLabel lblElemento = new JLabel("Elm");
lblElemento.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblElemento.setBounds(10, 52, 67, 14);
contentPane.add(lblElemento);
JLabel lblOxidacin = new JLabel("Ox");
lblOxidacin.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblOxidacin.setBounds(10, 77, 67, 14);
contentPane.add(lblOxidacin);
JLabel lblNAtmico = new JLabel("NAt");
lblNAtmico.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblNAtmico.setBounds(10, 102, 86, 14);
contentPane.add(lblNAtmico);
JLabel lblMAtmica = new JLabel("MAt");
lblMAtmica.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblMAtmica.setBounds(10, 127, 86, 14);
contentPane.add(lblMAtmica);
pass = new JPasswordField();
pass.setBounds(90, 166, 67, 20);
contentPane.add(pass);
JLabel lblPass = new JLabel("Pass");
lblPass.setFont(new Font("Courier Prime", Font.PLAIN, 11));
lblPass.setBounds(10, 169, 67, 14);
contentPane.add(lblPass);
smb = new JTextField();
smb.setBounds(67, 25, 86, 20);
contentPane.add(smb);
smb.setColumns(10);
elm = new JTextField();
elm.setColumns(10);
elm.setBounds(67, 47, 86, 20);
contentPane.add(elm);
ox = new JTextField();
ox.setColumns(10);
ox.setBounds(67, 72, 86, 20);
contentPane.add(ox);
nat = new JTextField();
nat.setColumns(10);
nat.setBounds(67, 97, 86, 20);
contentPane.add(nat);
mat = new JTextField();
mat.setColumns(10);
mat.setBounds(67, 127, 86, 20);
contentPane.add(mat);
JLabel lblResultado = new JLabel("");
lblResultado.setBounds(243, 232, 46, 14);
contentPane.add(lblResultado);
JButton compile = new JButton("Compile");
compile.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0) {
//COMPILE Presionado
//INSERT BETWEEN HERE
ox.setText("");
elm.setText("");
mat.setText("");
nat.setText("");
smb.setText("");
try {
Connection conexion=DriverManager.getConnection("jdbc:mysql://localhost/chem","root" ,"");
Statement comando=conexion.createStatement();
ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
if(registro.next()==true) {
smb.setText(registro.getString("simbolo"));
ox.setText(registro.getString("oxidacion"));
elm.setText(registro.getString("elemento"));
mat.setText(registro.getString("matom"));
} else {lblResultado.setText("No existe");}
conexion.close();
} catch(SQLException ex) {setTitle(ex.toString());}
//AND HERE
}
});
compile.setBounds(7, 194, 89, 23);
contentPane.add(compile);
JButton clear = new JButton("Clear");
clear.setBounds(7, 228, 89, 23);
contentPane.add(clear);
JButton alta = new JButton("Alta");
alta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//BOTON ALTA PRESIONADO
lblResultado.setText("");
try {
Connection conexion=DriverManager.getConnection("jdbc:mysql://localhost/chem","root", "");
Statement comando=conexion.createStatement();
comando.executeUpdate("insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")");
conexion.close();
lblResultado.setText("se registraron los datos");
elm.setText("");
ox.setText("");
nat.setText("");
mat.setText("");
smb.setText("");
} catch(SQLException ex){
setTitle(ex.toString());
}
}
});
alta.setBounds(335, 228, 89, 23);
contentPane.add(alta);
cargarDriver();
}
private void cargarDriver() {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception ex) {
setTitle(ex.toString());
}
}
}
Here is my database:
database phpmyadmin
And here is the exception when inserting 1 into NAt:
Actual Exception

Taking a look at your code around your select query, you are running
nat.setText("");
and then
ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
What do you expect nat.getText() to return here?
Of course, it will return "" because that's what you've set the text of nat to. You're then asking your database to run the following invalid query:
select elemento,simbolo,oxidacion,matom from form where natom=
Running this against a MySQL database will generate the error in your screenshot.
I'm guessing that the fix is to delete the line nat.setText("");.
However, instead of building up SQL strings using string concatenation, please use PreparedStatements instead.
Replace the lines
Statement comando=conexion.createStatement();
ResultSet registro = comando.executeQuery("select elemento,simbolo,oxidacion,matom from form where natom="+nat.getText());
with
PreparedStatement comando=conexion.prepareStatement(
"select elemento,simbolo,oxidacion,matom from form where natom=?");
comando.setInt(1, Integer.parseInt(nat.getText()));
ResultSet registro = comando.executeQuery();
and the lines
Statement comando=conexion.createStatement();
comando.executeUpdate("insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")");
with
Statement comando=conexion.prepareStatement(
"insert into form(elemento,simbolo,oxidacion,natom,matom) values (?,?,?,?,?)");
comando.setString(1, elm.getText());
comando.setString(2, smb.getText());
comando.setString(3, ox.getText());
comando.setString(4, Integer.parseInt(nat.getText()));
comando.setString(5, Integer.parseInt(mat.getText()));
comando.executeUpdate();
You will also need to add some error-handling around the calls to Integer.parseInt(...): these will throw NumberFormatException if either nat.getText() or mat.getText() isn't a valid integer.

If you could attach or describe exactly what the sqlException is that might help, but from what I can see your database connection url is malformed. So its probably not connecting to the database
your url is:
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/chem","root" ,"");
Normally you need to add a port number that the database is running on so changing the:
"jdbc:mysql://localhost/chem"
to:
jdbc:mysql://localhost:3306/chem
or whatever the port your database is running on, from a google it looks like the default port number is 3360 but it depends on how you have setup your database. But i think that should solve your problem

Please try to execute your sql query manually with your DB client.
To do this you can add code like this or use debugging to get the sql string value and test it:
String sqlString = "insert into form(elemento,simbolo,oxidacion,natom,matom) values ('"+elm.getText()+"','"+smb.getText()+"','"+ox.getText()+"',"+nat.getText()+","+mat.getText()+")";
System.out.println(sqlString);
comando.executeUpdate(sqlString);
You need to get the actual SQL string and test it manually if it works.

Related

How do I input data from java GUI into MS Access using UCanAccess

I'm new to using UCanAccess and Microsoft Access as a database for java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import net.ucanaccess.jdbc.*;
public class Memo extends JFrame implements ActionListener {
private JTextField textField;
private JTextField textField_1;
Connection cn = null;
ResultSet rs = null;
Statement s = null;
public Memo() {
getContentPane().setBackground(Color.DARK_GRAY);
getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(246, 0, 178, 50);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("Enter bill amount: $");
lblNewLabel.setFont(new Font("Arial Narrow", Font.BOLD, 11));
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(10, 0, 237, 50);
getContentPane().add(lblNewLabel);
JLabel label = new JLabel("Enter water usage amount(l): ");
label.setFont(new Font("Arial Narrow", Font.BOLD, 11));
label.setForeground(Color.WHITE);
label.setBounds(10, 49, 237, 50);
getContentPane().add(label);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(246, 49, 178, 50);
getContentPane().add(textField_1);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection cn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\decx\\Desktop\\Db.accdb");
String sql = "insert into db ('ID', 'WaterUsage', 'Bill') + values ('1', '12', '12')";
s = cn.createStatement();
s.executeUpdate(sql);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
btnSubmit.setFont(new Font("Arial Narrow", Font.BOLD, 11));
btnSubmit.setBounds(272, 131, 141, 35);
getContentPane().add(btnSubmit);
}
public static void main(String[] args) throws Exception {
Memo qMemo = new Memo();
qMemo.setSize(500, 350);
qMemo.setVisible(true);
qMemo.setTitle("Tips & Tricks");
qMemo.setDefaultCloseOperation(EXIT_ON_CLOSE);
qMemo.getContentPane().setLayout(null);
}
public void actionPerformed(ActionEvent e) {
}
}
I need to get the code to send data when the submit button is clicked. This is a school project where I have to allow users to enter water usage and bill (water utility bill), so I can display it later.
I have ran the code previously and but errors like "unexpected token" or "user has no privilege or object not found".
There are some notes :
You get this error (unexpected token) because the names of columns and table should not be between two quotes ''
The + operator is not allow in that position of query
Also, only the Strings can be between two quotes not the ints, make sure the type of ID for example is a String, if not you have to remove the two quotes
Read about Prepared Statement to avoid syntax error and to prevent SQL Injection
Look at :
String sql="insert into db ('ID', 'WaterUsage', 'Bill') + values ('1', '12', '12')";
//(1)-----------------------^--^--^----------^--^----^ ^ ^ ^
//(2)___________________________________________________| | |
//(3)_____________________________________________________________| |
That helped me a lot and with the help of my friends i completed my code, for anyone who might need this at any point, i'll be including my code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import net.ucanaccess.jdbc.*;
public class Memo extends JFrame implements ActionListener {
private JTextField textField;
private JTextField textField_1;
Connection cn = null;
ResultSet rs = null;
Statement s = null;
public Memo() {
getContentPane().setBackground(Color.DARK_GRAY);
getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(246, 0, 178, 50);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("Enter bill amount: $");
lblNewLabel.setFont(new Font("Arial Narrow", Font.BOLD, 11));
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(10, 0, 237, 50);
getContentPane().add(lblNewLabel);
JLabel label = new JLabel("Enter water usage amount(l): ");
label.setFont(new Font("Arial Narrow", Font.BOLD, 11));
label.setForeground(Color.WHITE);
label.setBounds(10, 49, 237, 50);
getContentPane().add(label);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(246, 49, 178, 50);
getContentPane().add(textField_1);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
int num = Integer.parseInt(textField.getText());
int num1 = Integer.parseInt(textField_1.getText());
textField.getText();
textField_1.getText();
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection cn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\DECX\\Desktop\\Db.accdb");
String sql = "insert into db (WaterUsage, Bill) values ('"+num+"', '"+num1+"')";
s = cn.createStatement();
s.executeUpdate(sql);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
btnSubmit.setFont(new Font("Arial Narrow", Font.BOLD, 11));
btnSubmit.setBounds(272, 131, 141, 35);
getContentPane().add(btnSubmit);
}
public static void main(String[] args) throws Exception {
Memo qMemo = new Memo();
qMemo.setSize(500, 350);
qMemo.setVisible(true);
qMemo.setTitle("Memo");
qMemo.setDefaultCloseOperation(EXIT_ON_CLOSE);
qMemo.getContentPane().setLayout(null);
}
public void actionPerformed(ActionEvent e) {
}
}

label name can not be resolved

I've created a label loginLabel to show message on wrong authentication. I've kept this logic inside actionPerformed method, but I am getting error as loginLabel can not be resolved. How to remove this error? I've created my GUI using window-builder.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class FirstView {
private JFrame frmFirstProject;
private JTextField txtUsername;
private JPasswordField txtPassword;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FirstView window = new FirstView();
window.frmFirstProject.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public FirstView() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmFirstProject = new JFrame();
frmFirstProject.getContentPane().setBackground(new Color(51, 204, 204));
frmFirstProject.setTitle("first project");
frmFirstProject.setBounds(100, 100, 714, 491);
frmFirstProject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmFirstProject.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(63, 47, 580, 354);
frmFirstProject.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(24, 25, 69, 22);
panel.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(24, 66, 69, 22);
panel.add(lblPassword);
txtUsername = new JTextField();
txtUsername.setBounds(97, 26, 86, 20);
panel.add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(97, 67, 86, 20);
panel.add(txtPassword);
JButton btnsubmit = new JButton("submit");
frmFirstProject.getRootPane().setDefaultButton(btnsubmit); //enter key
btnsubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int val = 0;
Connection sqlCon = DB_con.getSQLConnection();
PreparedStatement ps = sqlCon.prepareStatement("select 1 from tbl_user_info where username = ? and password = ?");
ps.setString(1, txtUsername.getText().toUpperCase());
ps.setString(2, String.valueOf(txtPassword.getPassword()).toUpperCase());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
val = rs.getInt(1);
}
if(val != 1)
{
loginLabel.setVisible(true);
}
System.out.println("the value is: "+val);
sqlCon.close();
System.exit(0);
} catch (Exception e) {
System.out.println(e.toString());
}
}
});
btnsubmit.setBounds(94, 125, 89, 23);
panel.add(btnsubmit);
JPanel panel_display = new JPanel();
panel_display.setBounds(36, 181, 355, 50);
panel.add(panel_display);
panel_display.setLayout(null);
JLabel loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
loginLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
loginLabel.setBounds(10, 11, 319, 28);
panel_display.add(loginLabel);
loginLabel.setVisible(false);
JLabel lbl_header = new JLabel("LIBRARY MANAGEMENT SYSTEM");
lbl_header.setFont(new Font("Tahoma", Font.BOLD, 14));
lbl_header.setBounds(211, 11, 288, 25);
frmFirstProject.getContentPane().add(lbl_header);
}
}
You are referring to the local variable loginLabel within the anonymous ActionListener class which you previously added to btnSubmit. This will not work as code inside the ActionListener class (or any other class) cannot see variables that are local to a method.
Instead you should declare loginLabel as a field, up at the top of the class:
private JPasswordField txtPassword;
private JLabel loginLabel;
This is visible to all methods inside the class and also any non-static classes defined inside your class (such as the aforementioned ActionListener).
Then simply change the line which creates your label inside your initialize() method from:
JLabel loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
to
loginLabel = new JLabel("Login Authentication Mismatched. Please try again.");
Defining the loginLabel before the ActionListener will be adequate in java 8, as java 8 implicitly marks local fields that are defined but never changed as final. If you are targetting java 7 or earlier you would need to explicitly make that variable final.
To avoid problems like "LabelX can not be resolved" or "ButtonY can not be resolved", I learned to do this:
On Eclipse, go to "Window" module...
Choose item "Preferences"...
Choose "WindowBuilder"...
Choose "Swing" or "SWT"...
In "Code Generation", choose "Field" in variable generation...
Inside "Event handlers", choose "Implement listener interface in parent class"...
It works using Java 1.7 or 1.8. Say bye bye to errors in ActionListner Class and GUI components Swing or SWT. And sure, i'm using WindowBuilder plugin to build the GUI application.

SQL Syntax Error In Java and MySql SELECT Query

I am developing a basic program that has 3 JFrames. A log-in, a registration and a Dashboard to be opened after successful log-in attempt. However, I am getting an error after typing in the username and password and clicking log-in button.
Here's the error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' password='1234'' at line 1
And here's my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.mysql.jdbc.Statement;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private JPanel contentPane;
private JTextField txtUsrName;
private JTextField txtPAss;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Login() {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 348);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblLogin = new JLabel("Welcome To TechApp");
lblLogin.setFont(new Font("Tekton Pro", Font.PLAIN, 18));
lblLogin.setBounds(135, 19, 163, 28);
contentPane.add(lblLogin);
JLabel lblUsername = new JLabel("UserName:");
lblUsername.setFont(new Font("Alaska", Font.PLAIN, 15));
lblUsername.setBounds(174, 58, 88, 28);
contentPane.add(lblUsername);
txtUsrName = new JTextField();
txtUsrName.setBounds(145, 90, 132, 20);
contentPane.add(txtUsrName);
txtUsrName.setColumns(10);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Alaska", Font.PLAIN, 15));
lblPassword.setBounds(182, 118, 95, 46);
contentPane.add(lblPassword);
txtPAss = new JTextField();
txtPAss.setColumns(10);
txtPAss.setBounds(145, 156, 132, 20);
contentPane.add(txtPAss);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String _username = txtUsrName.getText();
String _password = txtPAss.getText();
String url = "jdbc:mysql://127.0.0.1:3306/javabase";
String user = "java";
String passw = "password";
try{
// 1.Get a connection To Database
Connection myConn = DriverManager.getConnection(url, user, passw);
// 2.Create a statement
Statement myStmt = (Statement) myConn.createStatement();
// 3.Execute SQL Query
String sql = "SELECT userame, password FROM registration WHERE userame='"+_username+"', password='"+_password+"' ";
ResultSet result = myStmt.executeQuery(sql);
//myStmt.executeUpdate(sql);
int count = 0;
while(result.next()){
count = count + 1;
}
if(count == 1){
Dashboard frame = new Dashboard();
frame.setVisible(true);
}
else if(count > 1){
JOptionPane.showMessageDialog(null, "Duplicate User! Access Denied!");
}
else{
JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
btnNewButton.setBounds(169, 202, 89, 49);
contentPane.add(btnNewButton);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main frame = new Main();
frame.setVisible(true);
}
});
btnRegister.setBounds(168, 264, 89, 23);
contentPane.add(btnRegister);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setFont(new Font("Alaska", Font.PLAIN, 16));
lblNewLabel.setIcon(new ImageIcon("D:\\ExploitGate\\MAS-9831-Offwhite2.jpg"));
lblNewLabel.setBounds(0, 0, 434, 310);
contentPane.add(lblNewLabel);
}
}
I've searched the stackoverflow forum and carried out the possible solution given here
Can anyone please guide me how to handle this error?
Thanks In Advance :)
All of the above code is basically useless. It's an SQL syntax error, which means it's this one line:
... WHERE userame='"+_username+"', password='"+_password+"' ";
^---
you don't use , to separate where clause arguments. You use boolean operations. and, or, etc...
And note that you're vulnerable to sql injection attacks
You were using a comma , between your WHERE clauses rather than an AND.
String sql = "SELECT userame, password FROM registration WHERE userame='"+_username+"' AND password='"+_password+"' ";

NullPointerException on insert operation

I'm trying to insert into my database through the actionPerformed method for my button.
But i keep getting "java.lang.NullPointerException" The button press is supposed to insert from the textboxes and send it to the database, but i currently get a java null pointer exception in the actionperformed method. Can you help me?
(You can copy paste the code and run it directly if it would help)
(There is a connection to the Database, so it's not that)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JToolBar;
import javax.swing.JDesktopPane;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.JPasswordField;
import javax.swing.JList;
import javax.swing.JComboBox;
public class MyGuiApplication {
//database globals
private Connection con;
private Statement st;
private ResultSet rs;
//gui globals
private JFrame frame;
private JTextField EmailTextField;
private JTextField FirstNameTextField;
private JTextField LastNameTextField;
private JTextField MobileNumberTextField;
private JLabel lblPassword;
private JLabel lblConfirmPassword;
private JRadioButton MrsMsBTN;
private JRadioButton MrBTN;
private JLabel lblTitle;
private JLabel lblFirstName;
private JLabel lblLastName;
private JLabel lblMobileNumber;
private JLabel lblNewCustomer;
private JLabel lblDeliveryInformation;
private JLabel lblInCaseWe;
private JLabel lblMandatoryField;
private JPasswordField ConfirmPasswordField;
private JPasswordField PasswordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyGuiApplication window = new MyGuiApplication();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyGuiApplication() {
initialize();
DBConnect();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 456, 560);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//KNAPPEN
JButton btnUpdate = new JButton("update");
//ACTION LISTENER - TILFØJ DATA TIL DATABASEN VED TRYK PÅ KNAP
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
try
{
String sql="INSERT INTO customers (Email_Address, Password, User_ID, Title_Mr/Mrs, First_Name, Last_Name, Phone_Number, How_did_you_find_us?, Agree_to_terms_&_conditions, Receive_mails_and_offers?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement=con.prepareStatement(sql);
preparedStatement.setString (1, EmailTextField.getText()); // email addresse
preparedStatement.setString (2, PasswordField.getText()); // Stemme overens med ConfirmPasswordField?
preparedStatement.setInt (3, ((Integer) null)); //user ID primary key auto increment
preparedStatement.setString (4, "Mr"); // Title mrs/mr
preparedStatement.setString (5, FirstNameTextField.getText());
preparedStatement.setString (6, LastNameTextField.getText());
preparedStatement.setString (7, MobileNumberTextField.getText());
preparedStatement.setString (8, null); //dropdown menu, "how did you find us"?
preparedStatement.setBoolean(9, true); // agree to terms
preparedStatement.setBoolean(10, true); // receive email offers from us
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.print(e);
}
}
});
btnUpdate.setBounds(138, 474, 89, 23);
frame.getContentPane().add(btnUpdate);
EmailTextField = new JTextField();
EmailTextField.setBounds(163, 68, 186, 20);
frame.getContentPane().add(EmailTextField);
EmailTextField.setColumns(10);
FirstNameTextField = new JTextField();
FirstNameTextField.setBounds(163, 241, 186, 20);
frame.getContentPane().add(FirstNameTextField);
FirstNameTextField.setColumns(10);
LastNameTextField = new JTextField();
LastNameTextField.setBounds(163, 286, 186, 20);
frame.getContentPane().add(LastNameTextField);
LastNameTextField.setColumns(10);
MobileNumberTextField = new JTextField();
MobileNumberTextField.setBounds(163, 331, 186, 20);
frame.getContentPane().add(MobileNumberTextField);
MobileNumberTextField.setColumns(10);
JCheckBox TermsConditionsCheckBox = new JCheckBox("Yes, i agree to the Terms and Conditions.*");
TermsConditionsCheckBox.setBounds(115, 418, 266, 23);
frame.getContentPane().add(TermsConditionsCheckBox);
JCheckBox EmailOffersCheckBox = new JCheckBox("Yes, i wish to receiver Email offers from Zalando.");
EmailOffersCheckBox.setBounds(115, 444, 319, 23);
frame.getContentPane().add(EmailOffersCheckBox);
JLabel lblEmailAddress = new JLabel("Email Address*");
lblEmailAddress.setBounds(47, 71, 106, 14);
frame.getContentPane().add(lblEmailAddress);
lblPassword = new JLabel("Password*");
lblPassword.setBounds(65, 112, 88, 14);
frame.getContentPane().add(lblPassword);
lblConfirmPassword = new JLabel("Confirm password*");
lblConfirmPassword.setBounds(25, 143, 128, 14);
frame.getContentPane().add(lblConfirmPassword);
MrsMsBTN = new JRadioButton("Mrs./Ms.");
MrsMsBTN.setSelected(true);
MrsMsBTN.setBounds(138, 211, 76, 23);
frame.getContentPane().add(MrsMsBTN);
MrBTN = new JRadioButton("Mr.");
MrBTN.setBounds(216, 211, 109, 23);
frame.getContentPane().add(MrBTN);
lblTitle = new JLabel("Title*");
lblTitle.setBounds(95, 216, 37, 14);
frame.getContentPane().add(lblTitle);
lblFirstName = new JLabel("First name*");
lblFirstName.setBounds(65, 244, 88, 14);
frame.getContentPane().add(lblFirstName);
lblLastName = new JLabel("Last name*");
lblLastName.setBounds(65, 289, 88, 14);
frame.getContentPane().add(lblLastName);
lblMobileNumber = new JLabel("Mobile Number");
lblMobileNumber.setBounds(47, 334, 106, 14);
frame.getContentPane().add(lblMobileNumber);
lblNewCustomer = new JLabel("New Customer");
lblNewCustomer.setFont(new Font("Tahoma", Font.BOLD, 16));
lblNewCustomer.setBounds(25, 37, 149, 14);
frame.getContentPane().add(lblNewCustomer);
lblDeliveryInformation = new JLabel("Delivery information");
lblDeliveryInformation.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblDeliveryInformation.setBounds(10, 181, 109, 14);
frame.getContentPane().add(lblDeliveryInformation);
lblInCaseWe = new JLabel("In case we need to contact you about your order");
lblInCaseWe.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblInCaseWe.setBounds(163, 362, 251, 14);
frame.getContentPane().add(lblInCaseWe);
lblMandatoryField = new JLabel("* mandatory field");
lblMandatoryField.setFont(new Font("Tahoma", Font.ITALIC, 11));
lblMandatoryField.setBounds(25, 478, 100, 14);
frame.getContentPane().add(lblMandatoryField);
ConfirmPasswordField = new JPasswordField();
ConfirmPasswordField.setBounds(163, 142, 186, 20);
frame.getContentPane().add(ConfirmPasswordField);
PasswordField = new JPasswordField();
PasswordField.setBounds(163, 112, 186, 20);
frame.getContentPane().add(PasswordField);
JComboBox comboBox = new JComboBox();
comboBox.setBounds(163, 391, 186, 20);
//comboBox.add("Facebook.com", comboBox);
frame.getContentPane().add(comboBox);
JLabel lblHowDidYou = new JLabel("How did you find us?*");
//ADD OPTIONS TO WHERE YOU FOUND US
lblHowDidYou.setBounds(25, 394, 128, 14);
frame.getContentPane().add(lblHowDidYou);
}
public void DBConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/zalando", "root","");
st = con.createStatement();
}catch(Exception ex){
System.out.println("Error: " +ex);
}
}
}
}
Had you checked the not null fields in the database table.Copy the things in the output window.That's the stack trace.

java sql queries

I have a query. I have a database, and I am trying to write code, so that a record in the database can be created from the java software.
I have a connector class that connects to the database, then a registerStudent class, that lets the user type in value into 2 textfields. then the values should be used to create a record in the database table.
when i hit the submit button it gives me this error code:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at RegisterStudent$2.actionPerformed(RegisterStudent.java:99)
FYI - Line 99 Code =
con.stmt.executeUpdate("INSERT INTO staff (Name, Profession)"+"VALUES"+"("+"'"+name+"',"+"'"+profession+"')");
This is my code for the registerStudent class:
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
public class RegisterStudent
{
public RegisterStudent() {
initialize();
}
public JFrame frmRegisterStudent;
Connector con;
private JTextField textField_1;
private JTextField textField_2;
// initialise the frame
private void initialize() {
frmRegisterStudent = new JFrame();
frmRegisterStudent.setTitle("LEC AdminPro: RegisterStudents");
frmRegisterStudent.setBounds(100, 100, 413, 225);
frmRegisterStudent.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frmRegisterStudent.setLocationRelativeTo(null);
Border border = LineBorder.createGrayLineBorder();
frmRegisterStudent.getContentPane().setLayout(null);
con = new Connector();
JPanel panel_1 = new JPanel();
panel_1.setBounds(0, 0, 397, 189);
frmRegisterStudent.getContentPane().add(panel_1);
panel_1.setBorder(border);
panel_1.setLayout(null);
JLabel lblRegister = new JLabel("Register Student");
lblRegister.setFont(new Font("Tahoma", Font.BOLD, 12));
lblRegister.setBounds(10, 11, 124, 20);
panel_1.add(lblRegister);
JLabel lblSurname = new JLabel("Name");
lblSurname.setFont(new Font("Arial", Font.PLAIN, 11));
lblSurname.setBounds(10, 63, 69, 14);
panel_1.add(lblSurname);
JLabel lblDob = new JLabel("Profession");
lblDob.setFont(new Font("Arial", Font.PLAIN, 11));
lblDob.setBounds(10, 88, 69, 14);
panel_1.add(lblDob);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(104, 63, 266, 20);
panel_1.add(textField_1);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(104, 88, 266, 20);
panel_1.add(textField_2);
JButton btnNewButton = new JButton("Cancel");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Object[] options = {"Yes", "No"};
Component form = null;
int n = JOptionPane.showOptionDialog(form, "Would you like to cancel the new Registration?", "Exit Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options);
if(n == JOptionPane.YES_OPTION) {
frmRegisterStudent.setVisible(false);
}
}
});
btnNewButton.setBounds(280, 119, 89, 23);
panel_1.add(btnNewButton);
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String name = textField_1.getText();
String profession = textField_1.getText();
try {
con.stmt.executeUpdate("INSERT INTO staff (Name, Profession)"+"VALUES"+"("+"'"+name+"',"+"'"+profession+"')");
JOptionPane.showMessageDialog(frmRegisterStudent, "New Record has been added");
} catch (SQLException e) {
System.out.println("Record couldn't be added!");
e.printStackTrace();
}
}
});
button.setBounds(181, 119, 89, 23);
panel_1.add(button);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterStudent window = new RegisterStudent();
window.frmRegisterStudent.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void setVisible(boolean b) {
frmRegisterStudent.setVisible(true);
}
}
It looks like the problem is in the Connector class, which has a stmt field that does not get initialized.
Use this instead of the line with the NullPointerException
con.stmt = con.conn.prepareStatement("insert into staff (name, profession) values (?, ?)");
con.stmt.setString(1, name);
con.stmt.setString(2, profession);
con.stmt.executeUpdate();
But note that this is pretty bad design.
Is your connector null? I see the stmt is a field in the connector, have you initialized it?
By the way using a prepared statement is much better in your case, because it will escape the Strings (for example if they have "'" in them).
PreparedStatement pstmt = connection.prepareStatement("insert into staff (name, profession) values (?, ?)");
pstmt.setString(1, name);
pstmt.setString(2, profession);
pstmt.executeUpdate();

Categories

Resources