2017-02-21 204 views
0

我正在使用UDP Sockets編寫一個簡單的程序。我需要輸入患者的姓名並從數據庫中檢索其詳細信息。病人的名字在Doctor類中輸入併發送到服務器類。 Server類然後執行查詢來檢索患者的詳細信息。問題出在SQL語句中。當我只使用變量firstname時,它工作正常,但是當我把第二個變量姓氏放入PatientRecord變量時,它是NULL。Java SQL Select語句在WHERE子句中使用多個變量

服務器類:

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); 

     } 
    } 

} 

的醫生級別:

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(); 

    } 

} 
+0

名和姓是否匹配數據庫中的記錄? – brso05

+0

是的,當然,當我在SQL中自己寫這樣的名字就像這樣:「SELECT * FROM patient WHERE FirstName ='david'AND LastName ='john'」);它工作正常。當我使用變量firstname時,它才起作用。只有在使用這兩個變量時它才起作用 – Elliott08

+0

什麼'System.out.println(「First Name:」+ firstname); System.out.println(「Last Name:」+ lastname);'print copie over the exact results –

回答

1

這可能發生,所以爲了避免這種情況,你可以使用trim()這樣的:

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

你的方式來設置變量是不安全的它可以使語法錯誤或導致SQL注入這樣建議使用Prepapred Statement,這種方式是比較安全的,而不是使你的查詢,你可以使用:

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(); 

希望這能與您合作。

+0

謝謝!!!!我使用修剪(),它的工作原理!但是,我不明白爲什麼這是必要的,因爲輸入的名稱中沒有空格。 – Elliott08

+0

歡迎@ Elliott08 –

0

這顯然意味着,下面你WHERE條件不匹配的任何記錄,因此沒有記錄牽強。嘗試直接在SQL中運行查詢並查看您獲得的記錄數。或者嘗試將條件從AND更改爲OR,這應該給你一個想法。

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

順便說一句,你的代碼是開放的SQL Injection,因此考慮使用參數化查詢來代替。當你的字符串有空格

+0

查詢返回良好的結果,當這樣手動輸入名稱:WHERE FirstName ='david'AND LastName ='john' – Elliott08