database.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # This file is part of jwmud, written by Helmut Pozimski in 2014.
  2. #
  3. # jwmud is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, version 2 of the License.
  6. #
  7. # jwmud is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with jwmud. If not, see <http://www.gnu.org/licenses/>.
  14. # -*- coding: utf8 -*-
  15. import sqlite3
  16. from jwmudlib import jwmu_exceptions
  17. class db:
  18. def __init__(self, db_path):
  19. """Constructor, establishes the initial connection to the database."""
  20. try:
  21. self.__connection = sqlite3.connect(db_path)
  22. except sqlite3.OperationalError:
  23. raise jwmu_exceptions.DataBaseAccessFailed()
  24. else:
  25. self.__cursor = self.__connection.cursor()
  26. def __del__(self):
  27. """Destructor, closes the connection to the database"""
  28. self.__connection.close()
  29. def __ExecuteQuery(self, query, arguments=None):
  30. """Executes any query and returns the result"""
  31. if arguments is None:
  32. query_result = self.__cursor.execute(query)
  33. else:
  34. query_result = self.__cursor.execute(query, arguments)
  35. return query_result
  36. def __ExecuteStatement(self, statement, arguments=None):
  37. """Executes any statements that perform a write access to the
  38. database
  39. """
  40. try:
  41. if arguments is None:
  42. self.__cursor.execute(statement)
  43. else:
  44. self.__cursor.execute(statement, arguments)
  45. except sqlite3.OperationalError:
  46. raise jwmu_exceptions.DataBaseWriteFailed()
  47. else:
  48. self.__connection.commit()