def query_for_object(self, sql_query, args=None, required_type=None): """Execute a query that results in an int value, given static SQL. If args is provided, bind the arguments (to avoid SQL injection attacks).""" # This is the case where only two, non-named arguments were provided, the sql_query and one other. # If the second argument was 'args', it is invalid since 'required_type' is required. # It is was 'required_type', it shifted into 'args' position, and requires naming. if args and not required_type: raise ArgumentMustBeNamed(arg_name="required_type") results = self.query_for_list(sql_query, args) if len(results) != 1: raise IncorrectResultSizeDataAccessException( "Instead of getting one row, this query returned %s" % len(results)) if len(results[0]) != 1: raise IncorrectResultSizeDataAccessException( "Instead of getting one column, this query returned %s" % len(results[0])) equivalentTypes = [[types.UnicodeType, types.StringType]] if type(results[0][0]) != required_type: foundEquivType = False for equivType in equivalentTypes: if type(results[0] [0]) in equivType and required_type in equivType: foundEquivType = True break if not foundEquivType: raise DataAccessException("Expected %s, but instead got %s" % (required_type, type(results[0][0]))) return results[0][0]
def map_row(self, row, metadata=None): if metadata is not None: obj = self.clazz() for i, column in enumerate(metadata): setattr(obj, column["name"], row[i]) return obj else: raise DataAccessException( "metadata is None, unable to map result set into %s instance" % self.clazz)
def map_row(self, row, metadata=None): if metadata is not None: obj = {} for i, column in enumerate(metadata): obj[column["name"]] = row[i] return obj else: raise DataAccessException( "metadata is None, unable to convert result set into a dictionary" )
class DatabaseTemplate(object): """ This class is meant to mimic the Spring framework's JdbcTemplate class. Since Python doesn't use JDBC, the name is generalized to "Database" """ def __init__(self, connection_factory=None): self.connection_factory = connection_factory self.logger = logging.getLogger( "springpython.database.core.DatabaseTemplate") def __del__(self): "When this template goes out of scope, need to close the connection it formed." if self.connection_factory is not None: self.connection_factory.close() def _execute(self, sql_statement, args=None): """Issue a single SQL execute, typically a DDL statement.""" if args and type(args) not in self.connection_factory.acceptable_types: raise InvalidArgumentType(type(args), self.connection_factory.acceptable_types) sql_statement = self.connection_factory.convert_sql_binding( sql_statement) cursor = self.connection_factory.getConnection().cursor() error = None rows_affected = 0 try: try: if args: cursor.execute(sql_statement, args) rows_affected = cursor.rowcount lastrowid = cursor.lastrowid else: cursor.execute(sql_statement) rows_affected = cursor.rowcount lastrowid = cursor.lastrowid except Exception, e: self.logger.debug( "execute.execute: Trapped %s while trying to execute '%s'" % (e, sql_statement)) error = e finally: try: cursor.close() except Exception, e: self.logger.debug( "execute.close: Trapped %s, and throwing away." % e) if error: raise DataAccessException(error) return {"rows_affected": rows_affected, "lastrowid": lastrowid}
class DatabaseTemplate(object): """ This class is meant to mimic the Spring framework's JdbcTemplate class. Since Python doesn't use JDBC, the name is generalized to "Database" """ def __init__(self, connection_factory=None): self.connection_factory = connection_factory self.logger = logging.getLogger( "springpython.database.core.DatabaseTemplate") def __setattr__(self, name, value): """When the connection factory is set, initialize a connection to the database.""" self.__dict__[name] = value if name == "connection_factory" and value: self.__db = value.getConnection() def execute(self, sql_statement, args=None): """Issue a single SQL execute, typically a DDL statement.""" if args and type(args) not in self.connection_factory.acceptable_types: raise InvalidArgumentType(type(args), self.connection_factory.acceptable_types) sql_statement = self.connection_factory.convert_sql_binding( sql_statement) cursor = self.__db.cursor() error = None rows_affected = 0 try: try: if args: cursor.execute(sql_statement, args) rows_affected = cursor.rowcount else: cursor.execute(sql_statement) rows_affected = cursor.rowcount except Exception, e: self.logger.debug( "execute.execute: Trapped %s while trying to execute '%s'" % (e, sql_statement)) error = e finally: try: cursor.close() except Exception, e: self.logger.debug( "execute.close: Trapped %s, and throwing away." % e) if error: raise DataAccessException(error) return rows_affected
def do_in_tx_without_result(s, status): self.dt.execute("INSERT INTO animal (name) VALUES (?)", ('black mamba',)) self.assertEquals(len(self.dt.query_for_list("SELECT * FROM animal")), 1) raise DataAccessException("This should break the transaction, and rollback the insert.")