Monday 3 September 2018

Recover data from mysql db to textfield

I'm trying to implement a payroll system and got some issues with it. The program needs to be able retrieve data from mysql db to jtextfield.

when I try to search I get and error saying "com.mysql.jdbc.exception.jdbc4.MySQLSyntaxErrorException. You have an error in your SQL systax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1"
package AppPackage;

import java.sql.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AllowanceGUI extends javax.swing.JFrame {

Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;

public AllowanceGUI() {
    initComponents();
}

private void formWindowOpened(java.awt.event.WindowEvent evt) {
    conn=MySQLConnect.ConnectDb();
}                                 

private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

    try {
        String sql = "SELECT EmployeeID,FirstName,LastName,Designation,BasicSalary FROM EmployeeInfo WHERE EmployeeID =?";
        pst=conn.prepareStatement(sql);
        pst.setString(1,EmployeeIDSearchField.getText());

        rs = pst.executeQuery(sql);
    while(rs.next()) {
        EmployeeIDField.setText(rs.getString("EmployeeID"));
        FirstNameField.setText(rs.getString("FirstName"));
        LasNameField.setText(rs.getString("LastName"));
        DesignationField.setText(rs.getString("Designation"));
        BasicSalaryField.setText(rs.getString("BasicSalary"));

    }
    } catch (SQLException e ) {
    JOptionPane.showMessageDialog(null, e);

}}

my db connection is as below;
package AppPackage;
import java.sql.*;
import javax.swing.*;

public class MySQLConnect {
Connection conn = null;
public static Connection ConnectDb(){

    try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://Localhost/easypay","root","");
    return conn;
    }catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
    return null;

    }
}
}

can anybody please help me with this code?

you are doing
   pst=conn.prepareStatement(sql);// Prepare this sql query for me
    pst.setString(1,EmployeeIDSearchField.getText());// Attach this value as first parameter
    rs = pst.executeQuery(sql);// IGNORE EVERYTHING, Execute this query

you should do pst.executeQuery(); on the third line instead.
EDIT
Totally read over the fact it was a select. you should just do executeQuery without the string query. P.s. for greater speed use column indexes(integers) instead of column names in your rs.next() loop.

0 comments:

Post a Comment