2014-11-02 3 views
0

Как мне изменить этот код для создания объектов PreparedStatement (вместо объектов Statement)?Модификация моих методов для использования объектов PreparedStatement вместо объектов Statement

package com.cs330; 
    import javax.ws.rs.*; 
    import java.sql.Connection; 
    import java.sql.DriverManager; 
    import java.sql.ResultSet; 
    import java.sql.SQLException; 
    import java.sql.Statement; 

    @Path("ws2") 
    public class IngredientServices 
    @Path("/ingredients") 
    @GET 
    @Produces("text/plain") 
    public String getIngredients() throws SQLException, ClassNotFoundException { 

    String connectStr="jdbc:mysql://localhost:3306/fooddb"; 
    //database username 

    String username="root"; 
    //database password 

    String password="csci330pass"; 
    /* The driver is the Java class used for accessing 
     * a particular database. You must download this from 
     * the database vendor. 
     */ 

    String driver="com.mysql.jdbc.Driver"; 
    Class.forName(driver); 
    //Creates a connection object for your database 

    Connection con = DriverManager.getConnection(connectStr, username, password); 
    /* Creates a statement object to be executed on 
     * the attached database. 
     */ 

    Statement stmt = con.createStatement(); 
    /* Executes a database query and returns the results 
     * as a ResultSet object. 
     */ 

    ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient"); 
    /* This snippet shows how to parse a ResultSet object. 
     * Basically, you loop through the object sort of like 
     * a linkedlist, and use the getX methods to get data 
     * from the current row. Each time you call rs.next() 
     * it advances to the next row returned. 
     * The result variable is just used to compile all the 
     * data into one string. 
     */ 

     String result = ""; 
     while (rs.next()) 
     { 
     int theId = rs.getInt("id"); 
     String theName = rs.getString("name"); 
     String theCategory = rs.getString("category"); 
     result += "id: "+theId+ " , name: "+theName + "("+theCategory+")" + "\n" + "\n"; 
     } 
     return result; 
     }//END 

    @Path("/ingredients/{id}") 
    @GET 
    @Produces("text/plain") 
    public String getIngredientById(@PathParam("id") String theId) 
    throws SQLException, ClassNotFoundException { 
    int intId = 0; 
    try 
    { 
     intId = Integer.parseInt(theId); 
    } 
    catch (NumberFormatException FAIL) 
    { 
     intId = 1; 
    }//Obtaining an ingredient from the database 

    String connectStr="jdbc:mysql://localhost:3306/fooddb"; 
    String username="root"; 
    String password="csci330pass"; 
    String driver="com.mysql.jdbc.Driver"; 
    Class.forName(driver); 
    Connection con = DriverManager.getConnection(connectStr, username, password); 
    Statement stmt = con.createStatement(); 
    ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient 
    WHERE id=" +intId); 

    String result = ""; 
    while (rs.next()) 
    { 
     int theId2 = rs.getInt("id"); 
     String theName2 = rs.getString("name"); 
     String theCategory = rs.getString("category"); 
     result += "id: "+theId2+ " , name: "+theName2 + "("+theCategory+")" + "\n" + "\n"; 
    } 
     return result; 
    }//END METHOD 

    @Path("/ingredients/name") 
    @GET 
    @Produces("text/plain") 
    public String getIngredientByName(@QueryParam("name") String theName) 
    throws SQLException, ClassNotFoundException 
    { 
    //Obtaining an ingredient from the database 
    String connectStr="jdbc:mysql://localhost:3306/fooddb"; 
    String username="root"; 
    String password="csci330pass"; 
    String driver="com.mysql.jdbc.Driver"; 
    Class.forName(driver); 
    Connection con = DriverManager.getConnection(connectStr, username, password); 
    Statement stmt = con.createStatement(); 
    ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient WHERE 
    name='" + theName + "'"); 

    String result = ""; 
    while (rs.next()) 
    { 
     int theId3 = rs.getInt("id"); 
     String theName3 = rs.getString("name"); 
     String theCategory = rs.getString("category"); 
     result += "id: "+theId3+ " , name: "+theName3 + "("+theCategory+")" + "\n" + "\n"; 
    } 
     return result; 
    }//END METHOD 
    }//END CODE 

Я знаю то, что это не так просто, как просто изменить переменную объекта из заявления в PreparedStatement ... Вот почему я прошу некоторые предложения здесь. Спасибо.

+0

Посмотрите на это, http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/ – user75ponic

ответ

2

Несколько шагов:

  1. Изменить тип от Statement к PreparedStatement.
  2. Сохраните ваши запросы в String переменных. В любом месте, где вы должны использовать динамическое значение (например, места, где вы объединяете String), будут параметры для вашего запроса, замените эти переменные на ?.
  3. Создайте PreparedStatement используя Connection#prepareStatement, а не используя Connection.createStatement.
  4. Задайте параметры в PreparedStatement с помощью методов setXxx.
  5. Выполните инструкцию с помощью метода executeQuery.

Пример: PreparedStatement javadoc.

Это, как вы можете изменить getIngredientById метод, следуя инструкциям выше:

Connection con = DriverManager.getConnection(connectStr, username, password); 
//from "SELECT id, name, category FROM ingredient WHERE id=" + intId 
//check the usage of ? instead of intId 
String sql = "SELECT id, name, category FROM ingredient WHERE id = ?"; 
PreparedStatement pstmt = con.prepareStatement(sql); 
//setting variable in PreparedStatement 
pstmt.setInt(1, intId); 
ResultSet rs = pstmt.executeQuery(); 
String result = ""; 
while (rs.next()) { 
    //consume the data... 
} 

Это, как вы можете изменить getIngredientByName метод, следуя приведенным выше инструкциям:

Connection con = DriverManager.getConnection(connectStr, username, password); 
//? don't need you to escape it by using ' around 
//? is equals to the parameter, this is why using PreparedStatement is more safe 
//it will help you to avoid SQL Injection attacks 
String sql = "SELECT id, name, category FROM ingredient WHERE name = ?"; 
PreparedStatement pstmt = con.prepareStatement(sql); 
pstmt.setString(1, theName); 
ResultSet rs = pstmt.executeQuery(); 
String result = ""; 
while (rs.next()) { 
    //consume the data... 
} 

ли похожи на необходимые методы в вашем проекте.

+0

Мне не придется изменять части ToString, будет Я? Или я оставлю их такими? В любом случае, спасибо за некоторую свободу от того, что убивает меня здесь. – user2891351

+0

@ user2891351, если вы говорите о коде ResultSet, нет ничего, что можно было бы изменить. Кроме того, я бы рекомендовал использовать 'StringBuilder', а не конкатенацию строк, чтобы использовать данные запроса. –

+0

Прошу прощения: как бы я начал набирать код для getIngredientbyName ??? Я набрал это сам, но это явно не правильно, потому что я продолжаю получать только первый результат индекса, даже когда я печатаю полные имена других допустимых результатов, связанных с программой базы данных MySQL ... – user2891351

Смежные вопросы