sqlformatter.py 877 B

12345678910111213141516171819202122232425262728293031323334
  1. '''
  2. Formatter special pour les requetes SQL
  3. usage:
  4. Sql = SqlFormatter()
  5. my_query = Sql.format("SELECT {} FROM {}", "my_field", "tblname")
  6. @author: olivier.massot
  7. '''
  8. import string
  9. class SqlFormatter(string.Formatter):
  10. def format_field(self, value, format_spec):
  11. if value is None:
  12. return "Null"
  13. if format_spec == "date":
  14. return "#{:%Y-%m-%d %H:%M:%S}#".format(value)
  15. elif format_spec == "text":
  16. return "'{}'".format(SqlFormatter._escape(str(value)))
  17. elif format_spec == "float":
  18. return str(value).replace(",", ".")
  19. else:
  20. return SqlFormatter._escape(value.__format__(format_spec))
  21. @staticmethod
  22. def _escape(instr):
  23. return instr.replace("'", "''").replace("\"", "''").replace("\t", " ")