as the title suggests, ive been trying to delete data in a table in my SQLite through the use of a button. I have been able to make it work on another class, but i cant seem to make it work on this specific class which i will show you.
the button is called btnDelete, and the method that loads the database and deletes it is called delete_account.
Button btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Here's the whole code in the class just in case it is needed:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
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 AccSettings {
private JFrame frmAccountSett;
private JTextField txtFullname;
private JTextField txtUsername;
private JPasswordField txtPassword;
private int userid;
private String user;
/**
* Create the application.
*/
public AccSettings(String username) {
user=username;
//userid = id;
initialize();
edit_account();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAccountSett = new JFrame();
frmAccountSett.setTitle("Account Settings");
frmAccountSett.setBounds(100, 100, 450, 300);
frmAccountSett.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAccountSett.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Edit Username:");
lblUsername.setBounds(85, 62, 103, 14);
frmAccountSett.getContentPane().add(lblUsername);
txtUsername = new JTextField();
txtUsername.setBounds(229, 59, 137, 20);
frmAccountSett.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(229, 90, 137, 20);
frmAccountSett.getContentPane().add(txtPassword);
JButton btnConfirm = new JButton("Confirm Changes");
btnConfirm.setBounds(146, 164, 137, 29);
frmAccountSett.getContentPane().add(btnConfirm);
JLabel lblPassword = new JLabel("Edit Password:");
lblPassword.setBounds(85, 93, 103, 14);
frmAccountSett.getContentPane().add(lblPassword);
frmAccountSett.setVisible(true);
JButton btnDelete = new JButton("Delete Account");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
delete_account();
}
});
btnDelete.setBounds(299, 227, 125, 23);
frmAccountSett.getContentPane().add(btnDelete);
JButton btnBack = new JButton("<< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frmAccountSett.dispose();
}
});
btnBack.setBounds(10, 227, 103, 23);
frmAccountSett.getContentPane().add(btnBack);
JLabel lblFullname = new JLabel("Edit Fullname:");
lblFullname.setBounds(85, 31, 103, 14);
frmAccountSett.getContentPane().add(lblFullname);
txtFullname = new JTextField();
txtFullname.setColumns(10);
txtFullname.setBounds(229, 28, 137, 20);
frmAccountSett.getContentPane().add(txtFullname);
btnConfirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
update_account();
}
});
}
public void delete_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="DELETE FROM tblUsers WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Account successfully deleted!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
#SuppressWarnings("deprecation")
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"'"
+ "WHERE userID="+ userid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
//load the results
public void edit_account()
{
try {
Connection con; //create a variable for con
Database db = new Database(); //create an instance of database class
con = db.open_connection(); //set con as connection form database class
Statement st;
st = con.createStatement();
//create a statement variable
//create the query that will search the table based on similar terms
String query = "SELECT * FROM tblUsers WHERE userID=" + userid+ "";
//get the resultset of the query (rows)
ResultSet rs = st.executeQuery(query);
if (rs.next())
{
do{
txtFullname.setText(rs.getString(2));
txtUsername.setText(rs.getString(3));
txtPassword.setText(rs.getString(4));
}
while(rs.next());
}
/*
else {
JOptionPane.showMessageDialog(null, "Edit failed");
}
*/
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I believe the problem stems mostly from userID which zephyr has stated. I followed a code from another class(frmEditRef), but that class uses a JScrollPane, which when called from another class (frmMainInterface) looks like this:
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int x = table.getSelectedRow(); //get the current row
int ans = JOptionPane.showConfirmDialog(null, "Do you want to edit this record?");
if (ans == 0) {
//proceed to edit the transaction
//get the id
String id = String.valueOf(model.getValueAt(x, 0));
new EditRef(user,Integer.valueOf(id));
frmUserRef.dispose();
}
}
});
The class im trying to work with does not use JScrollPane. Therefore the coding to it would be different. Here's how it looks like from frmMainInterface:
btnAccountSett.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String id = ;
new AccSettings(user,Integer.valueOf(id));
}
});
As you can see, i have no idea what to put in after the "String id =".
I hope this explanation can get through you guys. I myself am having difficulty trying to explain something i dont even fully understand.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
this is my code an di get this error, I don't understand why, I tried multiple times to figure it out what is happening, are you able please to help me. I tried to check the several topic that are around here regarding this but nothing similar found and if I need to do a null check, I am new to this and I don't understand exactly what I need to do
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class JavaCrud {
private JPanel Main;
private JTextField txtName;
private JButton saveButton;
private JButton deleteButton;
private JButton updateButton;
private JTextField textField2;
private JTextField txtPrice;
private JTextField txtQty;
public static void main(String[] args) {
JFrame frame = new JFrame("JavaCrud");
frame.setContentPane(new JavaCrud().Main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public JavaCrud() {
Connect();
saveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name, price, qty;
name = txtName.getText();
price = txtPrice.getText();
qty = txtQty.getText();
try {
pst = con.prepareStatement("insert into products(pname,price,qty)values(?,?,?)");
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, qty);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Addedddddd!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String bid;
bid = textField2.getText();
try {
pst = con.prepareStatement("delete from products where pid = ?");
pst.setString(1, bid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Deleteeeeee!!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
textField2.setText("");
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
updateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String pid,name,price,qty;
name = txtName.getText();
price = txtPrice.getText();
qty = txtQty.getText();
pid = textField2.getText();
try {
pst = con.prepareStatement("update products set pname = ?,price = ?,qty = ? where pid = ?");
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, qty);
pst.setString(4, pid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Updateee!!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
textField2.setText("");
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
}
Connection con;
PreparedStatement pst;
public void Connect(){
try{
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/gbproducts","root","root");
System.out.println("Success");
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
A NullPointerException is thrown because you adding an addActionListener to your button that has not been instantiated.
In your JavaCrud() method you need to instantiate your buttons.
saveButton = new JButton("SAVE");
deleteButton = new JButton("DELETE");
updateButton = new JButton("UPDATE");
You would also need to instantiate your JTextfield because after a user clicks on a button you are trying to getText() from a JTextField that is null.
Also, it is better to implements ActionListener to your class than to addActionListener to every button. It allows for cleaner code and easier debugging.
Here you can read up on ActionListener Interface
I have Java jdk1.7xxx installed and a MySQL database v5.7 too.
My database is named "mydb".
I access it from the mysql console.
However when I try to access it from my java program it makes an error "source of data unknown, or pilot name not specified". So I am missing some pilot/extra file I guess. But I did import java.sql.* at the beginning of my program..
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import java.sql.*;
import java.util.*;
public class DPIA_impacts extends JFrame {
// Labels
JLabel lb_title;
JTable tableau = null;
static JPanel p_global, p_title, p_center, p_south;
JScrollPane scroll=null;
JButton btn_Save, btn_Export;
//DefaultTableModel model;
ArrayList t1=new ArrayList();
ArrayList t2=new ArrayList();
ArrayList t3=new ArrayList();
public DPIA_impacts(){
//declarations
p_global = new JPanel();
p_title = new JPanel();
p_center = new JPanel();
p_south = new JPanel();
lb_title = new JLabel("DPIA meeting: fill the table !");
btn_Save = new JButton("Save");
btn_Export = new JButton("Export");
scroll = new JScrollPane();
// add tool tip text to the Save and Export buttons
btn_Save.setToolTipText("Save to the database Impacts table");
btn_Export.setToolTipText("Exports the contents of the Jtable to an Excel file");
// add Action Listener to the buttons
btn_Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("You clicked the button SAVE");
String url = "jdbc:mysql://localhost/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
try {
//chargement du driver
Class.forName("com.mysql.jdbc.Driver");
// Recup connexion
cn = DriverManager.getConnection(url, login, passwd);
// Creation d'un statement
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
st.executeUpdate(sql);
//instruction.executeQuery(req);
} // Try
catch (SQLException ex)
{
System.out.println("Connexion à la base de données impossible");
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
System.out.println("Pilote de connexion introuvable");
ex.printStackTrace();
//}//end catch
} finally {
try{
cn.close();
st.close();
} catch (SQLException sqle){
sqle.printStackTrace();
}
}
}});
btn_Export.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Execute when button is pressed
System.out.println("You clicked the button EXPORT");
}
});
//add the components to the righ panels
p_title.add(lb_title);
p_center.add(scroll);
p_south.add(btn_Save, BorderLayout.WEST);
p_south.add(btn_Export, BorderLayout.EAST);
String req = "SELECT * FROM impacts";
int i =0;
Connect resultat = new Connect(req,1,"BaseDeDonnees");
// connexion a la base de donnees
}//end constructor
public static void main(String args[]) {
//Create and set up the window.
DPIA_impacts f = new DPIA_impacts();
f.setTitle("DPIA: check the impacts");
//f = new JFrame("DPIA: Impacts");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(p_title, BorderLayout.PAGE_START);
f.getContentPane().add(p_center, BorderLayout.CENTER);
f.getContentPane().add(p_south, BorderLayout.PAGE_END);
f.pack();
f.setSize(500, 300);
f.setVisible(true);
}//end main
}//end programm !
Adding the jar:
I think that in String url = "jdbc:mysql://localhost/mydb";
you forgot to write the port number.
try String url ="jdbc:mysql://127.0.0.1:3306/mydb";
UPDATE
Ok, just try this code and run it from Eclipse and not from cmd.
Also you use executeUpdate for INSERT. For SELECT you use executeQuery.
//Execute when button is pressed
System.out.println("You clicked the button SAVE");
String url = "jdbc:mysql://127.0.0.1:3306/mydb";
String login = "root";
String passwd = "toor";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
System.out.println("Connecting to database..");
try {
cn = DriverManager.getConnection(url, login, passwd);
System.out.println("Database Connected");
st = cn.createStatement();
String sql = "SELECT * FROM impacts";
rs = st.executeQuery(sql);
while (rs.next()){
//do something
}
//instruction.executeQuery(req);
} // Try
catch (SQLException ex)
{
System.out.println("Connexion à la base de données impossible");
ex.printStackTrace();
}
finally {
try{
if (cn != null ){
cn.close();
}
if (st != null ){
st.close();
}
if (rs != null ){
rs.close();
}
} catch (SQLException sqle){
sqle.printStackTrace();
}
}
I want to create a login page but it's not working properly. When I type in a username and password and click on the Login button, nothing is happening and I am not seeing any error message.
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Font;
public class acclogin extends JFrame {
Connection con;
Statement st;
ImageIcon bg = new ImageIcon("wb1.jpg");
JFrame f = new JFrame("User Login");
ResultSet rs;
JLabel l = new JLabel("Username");
JLabel l1 = new JLabel("Password");
JLabel l2 = new JLabel(bg);
JTextField t = new JTextField(15);
JPasswordField t1 = new JPasswordField(15);
JButton b = new JButton("Login");
public acclogin() {
frame();
}
public void frame() {
f.setSize(620, 300);
l.setBounds(10, 20, 100, 10);
t.setBounds(100, 20, 100, 20);
l1.setBounds(10, 50, 100, 80);
t1.setBounds(100, 70, 100, 20);
b.setBounds(100, 130, 100, 30);
l2.setBounds(0, 0, 600, 300);
f.add(l);
f.add(t);
f.add(l1);
f.add(t1);
f.add(b);
f.add(l2);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
LoginButton lb = new LoginButton();
b.addActionListener(lb);
}
class LoginButton implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj == b) {
try {
String user = t.getText().trim();
String pass = t1.getText().trim();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 = DriverManager.getConnection("jdbc:odbc:balogin");
Statement stat;
stat = con1.createStatement();
ResultSet rs = stat.executeQuery("select * from Table1 where user='" + user + "' and pass='" + pass + "'");
System.out.println("select * from Table1 where user='" + user + "' and pass='" + pass + "'");
int count = 0;
while (rs.next()) {
{
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "User Found,Access Granted");
ControlPanel cp1 = new ControlPanel();
cp1.display();
} else {
JOptionPane.showMessageDialog(null, "User not found");
}
}
} catch (Exception ex) {
}
}
}
}
public static void main(String args[]) {
new acclogin();
}
}
This is not exactly a solution for the problem, but this code has so many issues that you should solve before moving on.
This is what I would do:
split the code into multiple methods to take apart UI code from working with database
do not concat SQL query from strings, use prepared statement instead (omiting this could lead to an SQL injection, try login as ';DROP TABLE user;--)
usage of int count just for checking an existence of an element is confusing, you can use boolean or change SQL query to SELECT COUNT(*) ... or SELECT 1 IF EXISTS (SELECT * FROM ...)
you do not have to check the action event source, it will be always be the login button unless you assign the listener to something else
add e.printStackTrace() on catching exception
I also believe that you should use JPasswordTextField.getPassword() instead of getText()
remember closing ResultSet and Statement after use by calling .close()
try this :
Object obj = ae.getSource();
if ((JButton)obj ==(JButton)b) {
......... }
I know how to insert the comboBox value into sql but no idea on how to replace the comboBox value with number in sql.
This is some part of my comboBox coding and process button.
User.java
JComboBox comboBox_1 = new JComboBox();
comboBox_1.setBounds(126, 105, 140, 20);
contentPane.add(comboBox_1);
comboBox_1.addItem("RM100-RM200");
comboBox_1.addItem("RM200-RM300");
comboBox_1.addItem("RM300-RM400");
JButton btnNewButton = new JButton("Process");
btnNewButton.setBounds(360, 296, 89, 23);
contentPane.add(btnNewButton);
btnNewButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String a=(String)comboBox.getSelectedItem().toString();
Case ca= new Case();
try {
ca.addPlace(a);
LoginGUI um= new LoginGUI();
um.setVisible(true);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Case.java
public void addPlace( String r) throws Exception{
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Insert into menu(Budget)VALUES (?)";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setString(1,r);
ps.executeUpdate();
connect.close();
ps.close();
}
Let say the user select RM100-RM200, value "1" will be inserted into sql instead of RM100-RM200. Anyone can help?
Java comboboxes contain a getSelectedIndex method.
http://docs.oracle.com/javase/8/docs/api/javax/swing/JComboBox.html#getSelectedIndex--
Have you tested you code?
In your actionPerformed() you have written,
String a = (String) comboBox.getSelectedItem().toString();
The object comboBox is nowhere initialised in the code.
Do you mean comboBox_1 because it is the only object of JcomboBox which you have actually initialised in code.
Also
(String) comboBox.getSelectedItem().toString();
The typecast to String is actually not needed as toString return a String only.
I'm having a problem with GUI. When I click on JButton b1, when the text is empty in the JTextField text it does not catch the exception.
The query is executing only once when the button is clicked,if clicked again it throws exception and query is not executing
Code:
public class A extends JFrame{
private JTextField text;
private JButton b1;
private JLabel l1;
private Connection conn;
private Statement state;
private ResultSet set;
String server = "jdbc:mysql://localhost";
String user="tim";
String pass="u";
//query enter in textfield | select * from universty.student where rollno=2
public A() throws ClassNotFoundException, SQLException{
super("Frame");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(server,user,pass);
state = conn.createStatement();
getContentPane().setLayout(null);
text = new JTextField();
text.setBounds(35, 132, 346, 35);
getContentPane().add(text);
l1= new JLabel();
l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
l1.setBounds(35, 305, 384, 27);
getContentPane().add(l1);
b1 = new JButton("Submit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = text.getText();
set = state.executeQuery(query);
set.next();
String answer = set.getString(2);
l1.setText(answer);
}
catch (Exception e){
JOptionPane.showMessageDialog( null,
e.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
return;
}
finally{
try{
set.close();
state.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}});
b1.setBounds(132, 178, 129, 35);
getContentPane().add(b1);
setSize(450,450);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
}
Main Method:
public class Main {
public static void main(String args[]) throws ClassNotFoundException, SQLException{
A obj = new A();
}
}
You should open and close the database connection within your:
actionPerformed()
Since when you call your constructor it opens the db connection and closes it again. When you click the db connection is already closed again
public void actionPerformed(ActionEvent arg0) {
conn = DriverManager.getConnection(server,user,pass);
state = conn.createStatement();
//do query here
set.close();
state.close()
conn.close();
}
At the end of the first click, you close everything with following statement.
finally{
try{
set.close();
state.close();
conn.close();
That's why.
__UPDATE__
I am asked to provide a solution. Actually I have given half of the solution by pin-pointing the problem. But let me elaborate more, since I am asked.
Simple solution is not to close connection or statement or whatever. But this would be a bad solution, as unnecessary resources could be hold active. No need for that.
I do not know your application. So I can not give you a precise answer but rather, I can give you some guide lines and help you find the right answer by yourself.
Hold on to the resources, as long as you need them. And get rid of them as soon as you are done with them. For this case, If it is required user to click on that button and make a change in the database, then do not close connection etc but reuse them. If it is a multi-page application, you can close these resource when user moves to another page. (or activity if it a mobile app).
I hope it makes sense =]
I'm not sure of the purpose of your code but you should try and separate your view logic from your business logic. Also allowing a user to run SQL from a text box and submit button sounds dangerous, but if that's really what you want to do, here is one implementation you could use. Note the DAO here is not a true DAO because of the way you want to execute a query
public class A extends JFrame {
private final JTextField text;
private final JButton b1;
private final JLabel l1;
private AService service;
public A() {
super("Frame");
service = new AServiceImpl(new ADAOJDBCImpl());
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
text = new JTextField();
text.setBounds(35, 132, 346, 35);
getContentPane().add(text);
l1= new JLabel();
l1.setFont(new Font("Tahoma", Font.PLAIN, 22));
l1.setBounds(35, 305, 384, 27);
getContentPane().add(l1);
b1 = new JButton("Submit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String query = text.getText();
try {
String answer = service.executeQuery(query);
l1.setText(answer);
} catch (SQLException e){
JOptionPane.showMessageDialog( null,
e.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE );
return;
}
}});
b1.setBounds(132, 178, 129, 35);
getContentPane().add(b1);
setSize(450,450);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
pack();
setVisible(true);
}
}
public interface AService {
public String executeQuery(String query) throws SQLException;
}
public class AServiceImpl implements AService {
private ADAO dao;
public AServiceImpl(ADAO dao) {
this.dao = doa;
}
#Override
public String executeQuery(String query) throws SQLException {
return dao.executeQuery();
}
}
/**
* Note usually a DAO is specfically for accessing data, NOT
* for executing User defined queries from a GUI text box
* so it would usually have methods such as add, find, delete, update etc.
*/
public interface ADAO {
public String executeQuery(String query) throws SQLException;
}
public class ADAOJDBCImpl implements ADAO {
#Override
public String executeQuery(String query) throws SQLException {
String server = "jdbc:mysql://localhost";
String user="tim";
String pass="u";
String answer = "":
try (Connection conn = DriverManager.getConnection(server,user,pass);
Statement state = conn.createStatement();
ResultSet set = state.executeQuery(query);) {
if(set.next()) {
answer = set.getString(2);
}
}
return answer;
}
}