Newbie question... plz help!


Web tier: servlets, JSP, Web frameworks: Newbie question... plz help!

  1. Newbie question... plz help! (2 messages)

    how can parse a string before inserting it into a database (filter quotes...)? in php there is a function called add_slashes/strip_slashes... anything similar in java???

    Threaded Messages (2)

  2. Newbie question... plz help![ Go to top ]

    you should use prepared statements. when you use the setString method, things get automatically escaped. i have a method that does it for you. it's not pretty but if you don't want to learn prepared statements, then let me know and i'll post it here...

    after you get your connection,

    // ugly code starts here
    import java.util.StringBuffer;
    import java.sql.*;


    // build a query
    StringBuffer buf = new StringBuffer(1024);
    buf.append("INSERT INTO person ");
    buf.append("(name, age, quote) ");
    buf.append("VALUES(?, ?, ?) ");

    String quote = "i ain't don't can't won't english";

    // prepare our variables
    PreparedStatement pstmt = null;
    Connection con = null;

    try {

      // get database connection, don't use this code
      // sample only =p
      con = pool.getConnection();

      // prepare statement
      pstmt = con.prepareStatement(buf.toString());
      // now set parameters
      pstmt.setString(1, 'Joseph'); // name
      pstmt.setInt(2, 18); // age
      pstmt.setString(3, quote); // aha! quote

      // the string quote gets auto-escaped

    } catch (SQLException ex) {
      System.out.println("WTF!!! =(");
  3. Newbie question... plz help![ Go to top ]

    thanks a lot! now it's working great...