Elegent solution to replacing ' and " ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • fyleow

    #1

    Elegent solution to replacing ' and " ?

    I'm trying to replace the ' and " characters in the strings I get from
    feedparser so I can enter it in the database without getting errors.
    Here's what I have right now.

    self.title = entry.title.enc ode('utf-8')
    self.title = self.title.repl ace('\"', '\\\"')
    self.title = self.title.repl ace('\'', '\\\'')

    This works just great but is there a more elegent way to do this? It
    looks like maybe I could use the translate method but I'm not sure.

  • Jim

    #2
    Re: Elegent solution to replacing ' and " ?

    Are you sure that your dB interface module doesn't do this for you?
    What dB and interface are you using?

    Jim

    Comment

    • Serge Orlov

      #3
      Re: Elegent solution to replacing ' and " ?

      fyleow wrote:[color=blue]
      > I'm trying to replace the ' and " characters in the strings I get from
      > feedparser so I can enter it in the database without getting errors.
      > Here's what I have right now.
      >
      > self.title = entry.title.enc ode('utf-8')
      > self.title = self.title.repl ace('\"', '\\\"')
      > self.title = self.title.repl ace('\'', '\\\'')
      >
      > This works just great but is there a more elegent way to do this? It
      > looks like maybe I could use the translate method but I'm not sure.[/color]

      You should use execute method to construct sql statements. This is
      wrong:

      self.title = entry.title.enc ode('utf-8')
      self.title = self.title.repl ace('\"', '\\\"')
      self.title = self.title.repl ace('\'', '\\\'')
      cursor.execute( 'select foo from bar where baz="%s" ' % self.title)

      This is right:

      self.title = entry.title
      cursor.execute( "select foo from bar where baz=%s", (self.title,))

      The formatting style differs between db modules, take a look at
      paramstyle description in PEP 249:
      This API has been defined to encourage similarity between the Python modules that are used to access databases. By doing this, we hope to achieve a consistency leading to more easily understood modules, code that is generally more portable across datab...


      Comment

      • fyleow

        #4
        Re: Elegent solution to replacing ' and " ?

        I'm using PyGreSQL on a PostgreSQL db.

        I didn't even include my SQL but Serge guessed right and that's what I
        had. I changed it and it works now.

        Thanks for the help! :)

        Comment

        Working...