2014-11-02 53 views
0

如何修改此代碼以使用PreparedStatement對象(而不是語句對象)?修改我的方法以使用PreparedStatement對象而不是語句對象

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 2014-11-02 11:49:30

回答

2

幾個步驟:

  1. 變化從StatementPreparedStatement類型。
  2. 將您的查詢存儲在String變量中。您應該使用動態值的任何位置(例如,連接String的位置)將作爲查詢的參數,將這些變量替換爲?
  3. 通過使用Connection#prepareStatement而不是使用Connection.createStatement來創建PreparedStatement
  4. 使用setXxx方法在PreparedStatement中設置參數。
  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 2014-11-02 12:50:31

+0

@ user2891351如果您正在討論'ResultSet'代碼,則不需要更改。另外,我建議使用'StringBuilder'而不是字符串連接來使用查詢的數據。 – 2014-11-02 12:53:55

+0

我很抱歉問:我會如何去輸入getIngredientbyName的代碼?我自己輸入了它,但顯然是不正確的,因爲我一直只得到索引的第一個結果,即使我輸入了MySQL數據庫程序中其他有效結果的全名... – user2891351 2014-11-03 19:35:35

相關問題