Java SQL Select statement using several variables in WHERE clause

孤人 提交于 2021-02-11 09:17:11

问题


I am writing a simple program using UDP Sockets.I need to input the name of a patient and retrieve its details from the database. The name of the patient is entered in the Doctor class and sent to the Server Class. The Server class then execute a query to retrieve the details of the patient. The problem is in the SQL statement. When I used only the variable firstname it is working fine, but when I put the second variable lastname the PatientRecord variable is NULL.

The Server Class :

public class Server {

    public static Connection con;

    public static String PatientRecords;

    public static String QueryPatientInfo(String PatientDetails) throws SQLException {

        System.out.print("\nNew Patient query received:\n");

        String [] PatientDetArray = PatientDetails.split(",");

        String firstname,lastname;

        firstname = PatientDetArray[1];
        lastname  = PatientDetArray[2];

        System.out.println("First Name: "+ firstname);
        System.out.println("Last Name: "+ lastname);

        Statement query = con.createStatement();

        query.execute("SELECT * FROM patient WHERE FirstName = '"+firstname+"'  AND LastName = '"+lastname+"' ");

        ResultSet rs = query.getResultSet();

        String sex;
        String dob ;
        String address ;
        String occupation;
        String phoneno  ;


        if(rs != null){

            while (rs.next()){

                sex = rs.getString("Sex");
                dob = rs.getString("DOB");
                address = rs.getString("Address");
                occupation = rs.getString("Occupation");
                phoneno = rs.getString("PhoneNo");

                PatientRecords = sex + "," + dob + "," + address + "," + occupation + "," + phoneno;
            }

            System.out.print("Patient records successfully retrieved from database !\n\n");

            return PatientRecords;
        }

        else {

            System.out.print("Error occurred patient records not found !\n\n");

            return "Error occurred patient records not found !";
        }

    }

    public static void main(String[] args) throws IOException, SQLException {

        // Connecting to database - using xampp

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/patientrecord", "root", "");
            System.out.println("Database is connected !");

        }
        catch(Exception e)
        {
            System.out.println("Database connection error: " + e);
        }

        DatagramSocket serverSocket = new DatagramSocket(8008);

        byte[] receiveData = new byte[1024];

        byte[] sendData;

        System.out.println("Server ready and waiting for clients to connect...");

        while (true) {

            DatagramPacket receivePacket =  new DatagramPacket(receiveData, receiveData.length);

            serverSocket.receive(receivePacket);

            String PatientDetails = new String(receivePacket.getData());

            String message;

            message = QueryPatientInfo(PatientDetails);

            System.out.print(message);

            InetAddress IPAddress = receivePacket.getAddress();

            int port = receivePacket.getPort();

            sendData = message.getBytes();

            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);

            serverSocket.send(sendPacket);

        }
    }

}

The Doctor Class :

public class Doctor {

    public static void main(String[] args) throws IOException {


        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

        DatagramSocket clientSocket = new DatagramSocket();

        InetAddress IPAddress = InetAddress.getByName("localhost");

        // Creating array of bytes to send and receive packet
        byte[] sendData;

        byte[] receiveData = new byte[1024];

        String request,firstName,lastName;

        request = "query";

        System.out.print("Patient Registration");

        System.out.print("\n\nEnter Patient Details:\n");

        // User input
        System.out.print("First name: \n");

        firstName= inFromUser.readLine();

        System.out.print("Last name: \n");
        lastName = inFromUser.readLine();

        String PatientDetails = request + ","+ firstName + "," +lastName;

        sendData = PatientDetails.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,IPAddress, 8008);

        // Send data packet to server
        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        //Receive data packet from server
        clientSocket.receive(receivePacket);

        String PatientRecords =  new String(receivePacket.getData());

        //System.out.print(PatientRecords);

        String [] PatientDetArray = PatientRecords.split(",");

        String sex,dob,address,occupation,phoneno;

        sex = PatientDetArray[0];
        dob = PatientDetArray[1];
        address = PatientDetArray[2];
        occupation = PatientDetArray[3];
        phoneno = PatientDetArray[4];

        System.out.println("FROM SERVER: ");

        System.out.println("Details for patient : " + firstName + " " + lastName);
        System.out.println("Sex: " + sex);
        System.out.println("Date of birth: " +dob );
        System.out.println("Address: " + address );
        System.out.println("Occupation: " + occupation);
        System.out.println("Phone number: " + phoneno);

        clientSocket.close();

    }

}

回答1:


This can happen when your String have Spaces so to avoid this situation you can use trim() like this :

query.execute("SELECT * FROM patient WHERE FirstName = '" + firstname.trim() + 
               "'  AND LastName = '" + lastname.trim() + "' ");

Your way to set variables is not secure it can make syntax error or cause an SQL Injection so suggest to use Prepapred Statement, this way is more secure so instead your query you can use :

PreparedStatement preparedStatement = connection.prepareCall("SELECT * FROM patient WHERE FirstName = ? AND LastName = ? ");
preparedStatement.setString(1, firstname.trim());
preparedStatement.setString(2, lastname.trim());
ResultSet result = preparedStatement.executeQuery();

Hope this can work with you.




回答2:


That clearly means that your WHERE condition as below is not matching any records and thus no records fetched. Try running the query in SQL directly and see how many records you get. Or try changing the condition from AND to OR and that should give you an idea.

WHERE FirstName = '"+firstname+"'  AND LastName = '"+lastname+"' 

BTW, your code is open to SQL Injection and thus consider using a parameterized query instead.



来源:https://stackoverflow.com/questions/42377124/java-sql-select-statement-using-several-variables-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!