SQL Syntax Error In Java and MySql SELECT Query - java

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+"' ";

Related

I want to present the username from database JAVA Jframe

I have two JFrame windows one for the login and the second for the welcome. Now I want to present the Firstname and the Lastname of the connected user near to the hello in the welcome screen.
I tried many things but none of them worked so I'm asking for you help. I just started to learn GUI:
The login code:
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frame;
private JLabel MainLogo;
String Firstname=null;
String Lastname=null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
Connection connected = null;
private JTextField UsernameFiled;
private JPasswordField passwordField;
public Login() {
initialize();
connected = DBConnection.DBconnector();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 560, 256);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("UserName: ");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
lblNewLabel.setBounds(160, 11, 140, 50);
frame.getContentPane().add(lblNewLabel);
JLabel lblPassword = new JLabel("PassWord: ");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 20));
lblPassword.setBounds(160, 72, 140, 40);
frame.getContentPane().add(lblPassword);
JButton Loginbtn = new JButton("Login");
Loginbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select * from Users where nickname=? and password=?";
PreparedStatement pst = connected.prepareStatement(query);
pst.setString(1, UsernameFiled.getText());
pst.setString(2, passwordField.getText());
ResultSet res = pst.executeQuery();
Firstname = res.getString("Firstname");
Lastname = res.getString("Lastname");
int c=0;
while(res.next()) {
c++;
}
if(c == 0) {
JOptionPane.showMessageDialog(null, "You didnt put any username or password!");
}
else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage();
UserFrame.setVisible(true);
}else if( c > 1) {
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}else {
JOptionPane.showMessageDialog(null, "Username and Password are inncorect...Try agian!");
}
pst.close();
res.close();
}catch(Exception LoginError) {
JOptionPane.showMessageDialog(null, LoginError);
}
}
});
Loginbtn.setFont(new Font("Tahoma", Font.BOLD, 20));
Loginbtn.setBounds(160, 148, 186, 40);
frame.getContentPane().add(Loginbtn);
UsernameFiled = new JTextField();
UsernameFiled.setFont(new Font("Tahoma", Font.BOLD, 16));
UsernameFiled.setBounds(310, 28, 186, 25);
frame.getContentPane().add(UsernameFiled);
UsernameFiled.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.BOLD, 16));
passwordField.setBounds(310, 84, 186, 25);
frame.getContentPane().add(passwordField);
MainLogo = new JLabel("");
Image imgs = new ImageIcon(this.getClass().getResource("/login.png")).getImage();
MainLogo.setIcon(new ImageIcon(imgs));
MainLogo.setBounds(10, 11, 128, 128);
frame.getContentPane().add(MainLogo);
}
}
The Welcome Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UserPage extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserPage frame = new UserPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connected=null;
private JTable table;
public UserPage() {
connected=DBConnection.DBPreconnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 576, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton bntLoadData = new JButton("Show Users Data");
bntLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select ID,Age,Password,Firstname,Lastname from users";
PreparedStatement pst = connected.prepareStatement(query);
ResultSet res = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(res));
} catch (Exception Error) {
Error.printStackTrace();
}
}
});
JLabel lblNewLabel = new JLabel("Hello, " + "The Username name");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 18));
lblNewLabel.setBounds(10, 11, 280, 19);
contentPane.add(lblNewLabel);
bntLoadData.setFont(new Font("Tahoma", Font.BOLD, 20));
bntLoadData.setBounds(162, 102, 238, 23);
contentPane.add(bntLoadData);
table = new JTable();
table.setBounds(28, 136, 508, 221);
contentPane.add(table);
}
}
In your code, you does not seem to load the username or password of the logged in user at the welcome frame. Either you will have to pass that from the login frame or you will have to re-query the database and get firstname and lastname.
I suggest, simply pass the firstname and lastname from welcome screen via constructor.
In successful login, simply pass the name in the constructor: Login code addition:
} else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage( Firstname, Lastname );
UserFrame.setVisible(true);
}
In the welcome frame, add a constructor to handle this:
public UserPage(String loggedInFirstName, String loggedInLastName){
// your remaining code
JLabel lblNewLabel = new JLabel("Hello, " + loggedInFirstName + " " + loggedInLastName );
// your remaining code.
}
A approach like this might work for your case and don't forget to mark the answer as accepted if this works for you

Exception during connection to JDBC MySQL

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.

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) {
}
}

How to connect Java classes to GUI?

I'm designing a database that can be accessed through a GUI, I have three classes Main, Database and GUI, When I run the main I get an error and the GUI closes followed by a brief error message which I cannot read, not sure where this is going wrong as i believe it can be a number of issues. Thanks for all your help :)
Here is my main class
public class MainApplication {
#SuppressWarnings("unused")
public static void main(String[] args) {
VideoStoreGUI window = new VideoStoreGUI();
}
}
My Database Class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import javax.swing.JOptionPane;
#SuppressWarnings("unused")
public class DataBase {
static Connection con = null;
static Statement stmt = null;
static ResultSet rs = null;
static Scanner in = new Scanner(System.in);
public void close_connection() {
try
{
con.close();
System.out.println("Database Connections Succesully Closed.");
}
catch (SQLException sqle)
{
System.out.println("Error: failed to close the database");
}
}
public static void addMember(int member_id, String name, String address) // Adding a Member to the Database.
{
try {
String str = "INSERT INTO members (member_id, name, address) values(" + member_id + ", '" + name + "', '"
+ address + "');";
int rows = stmt.executeUpdate(str);
System.out.println("Success in adding member");
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error: Could not add member");
}
}
public static void initialize_database() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/videostore";
con = DriverManager.getConnection(url, "root", "admin");
stmt = con.createStatement();
} catch (Exception e) {
System.out.println("Error: Failed to connect to database\n" + e.getMessage());
}
}
public DataBase()
{
initialize_database();
}
}
and my GUI class:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JMenuBar;
public class VideoStoreGUI extends JFrame {
private JFrame frame;
DataBase my_database;
private JPanel contentPane;
private JTextField textMemberID;
private JTextField textMemberName;
private JTextField textMemberAddress;
/**
* Create the frame.
*/
public VideoStoreGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 400);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 31, 232, 240);
contentPane.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("Members", null, panel, null);
panel.setLayout(null);
JLabel labelMemberID = new JLabel("Members ID");
labelMemberID.setBounds(10, 11, 85, 14);
panel.add(labelMemberID);
JLabel labelMemberName = new JLabel("Members Name");
labelMemberName.setBounds(10, 36, 85, 14);
panel.add(labelMemberName);
JLabel labelMemberAddress = new JLabel("Members Address");
labelMemberAddress.setBounds(10, 61, 85, 14);
panel.add(labelMemberAddress);
textMemberID = new JTextField();
textMemberID.setBounds(131, 8, 86, 20);
panel.add(textMemberID);
textMemberID.setColumns(10);
textMemberName = new JTextField();
textMemberName.setColumns(10);
textMemberName.setBounds(131, 33, 86, 20);
panel.add(textMemberName);
textMemberAddress = new JTextField();
textMemberAddress.setColumns(10);
textMemberAddress.setBounds(131, 58, 86, 20);
panel.add(textMemberAddress);
JButton buttonAddMember = new JButton("Add Member");
buttonAddMember.setBounds(10, 86, 102, 23);
panel.add(buttonAddMember);
JButton buttonRemoveMember = new JButton("Add Member");
buttonRemoveMember.setBounds(115, 86, 102, 23);
panel.add(buttonRemoveMember);
JButton buttonSearchMember = new JButton("Add Member");
buttonSearchMember.setBounds(66, 120, 102, 23);
panel.add(buttonSearchMember);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("Products", null, panel_1, null);
}
}
I see only one place where you can get popup. You can keep it if you like but add system output and be sure about your message:
catch (SQLException sqle) {
System.out.writeln("Exception:"+sqle);
JOptionPane.showMessageDialog(null, "Error: Could not add member");
}
Based on place of this message I think you have wrong sql or database. I would suggest that you print your sql and results of it too.
The main reason this was not working for me was because I had removed setVisable(true) from the GUI and forgot to add it back to the method, I was then receiving an Error "AWT-EventQueue-0" this was to do with the way my database connection was set up, removing and adding the JDBC driver again resolved this.

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