2015-06-12 44 views
0

我不知道爲什麼我得到這個。以下是我嘗試從數據庫檢索某些信息並將其作爲對映射到特定URL的Jersey資源的響應發送的一些代碼。我不知道,y是什麼theerror指:發生錯誤:語法錯誤:意外的令牌y

public String myInformation(String theName){ 

     String infoQuery = "Select * from bookinfo where name= \'theName\'"; 
     ResultSet result = null; 
     conn = newConnection.dbConnection(); 

     try 
     { 

      preparedStatement = conn.prepareStatement(infoQuery); 
      result = preparedStatement.executeQuery(infoQuery); 
     } 
     catch (SQLException e) 
     { 
      e.printStackTrace(); 
     } 
     StringBuilder information = new StringBuilder(); 
     try 
     { 
      if(result != null){ 
       while(result.next()){ 

       // Build the string which is returned from this 
       // method and sent as json response for a URL of a resource 

      I read columns from database and use StringBuilder to store it.       At the end I convert it to String and pass it to Jersey resource. 
      } 

else{ 
       System.out.println("No result"); 
      } 
     } 
     catch (SQLException e) 
     { 
      e.printStackTrace(); 
     } 
     String someInformation = information.toString(); 
     return someInformation; 
} 

在我的資源:

@GET 
    @Path("/allSome/{theName}") 
    @Produces(MediaType.APPLICATION_JSON) 
    public Response getSomeInfo(@PathParam("theName") String theName){ 

     System.out.println("Name is: "+ theName); 
     BookInformation bookInfo = new BookInformation(); 
     String bookInformation =bookInfo.bookInformation(bookName); 

     ResponseBuilder responseBuilder = Response.status(Status.OK); 
     responseBuilder.entity(bookInformation); 

     Response response = responseBuilder.build(); 
     return response; 
    } 

編輯

我的方法返回一個字符串。在Postman客戶端上,我正從數據庫接收數據,但它以字符串的形式返回,它們之間沒有空格。我想我需要將該字符串轉換爲JSON,以便我的資源可以將其發送回客戶端以在頁面上顯示。

任何幫助表示讚賞。謝謝。

+0

你可以發佈更多的代碼,例如,這個代碼被調用的地方,而你是完整的錯誤信息? – mcraen

回答

0

'y'必須在theName參數中,以及一些引號。您應該使用PreparedStatement得當,有一個佔位符參數:

String infoQuery = "Select * from bookinfo where name = ?"; 
// ... 
preparedStatement = conn.prepareStatement(infoQuery); 
preparedStatement.setString(1, theName); 
// ... 

您的代碼結構不佳。取決於try塊成功的代碼應該在try塊內。

+0

我仍然需要使用轉義字符,儘管我認爲查詢才能正常工作。我曾嘗試做上述解決方案,但遇到了錯誤:「意外的輸入結束,您的SQL語法出錯;查看與您的MySQL服務器版本相對應的手冊,以找到在'?'附近使用的正確語法。在第1行「..這就是爲什麼我試圖把實際的術語用於查詢和檢查如何避開這些轉義序列。現在我回到了同樣的錯誤。 – user3044240

+0

我不認爲需要轉義角色。我的JavaScript雖然能夠取得進展。雖然我正在接收文本,但是我在Ajax中調用JSON時已將數據類型設置爲錯誤。但是錯誤在String infoQuery定義的部分仍然存在。它現在提供了錯誤信息「com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:你的SQL語法有錯誤;請查看與你的MySQL服務器版本相對應的手冊,以便在'?'附近使用正確的語法。在第1行「。 – user3044240