SqlExecutor

Introduction

This is a static class that provides a thin wrapper around JDBC. It has only two types of static methods: executing non-query SQL statements and executing query SQL statements.

Usage

Connection conn = null;
try {
	conn = ds.getConnection();
	// Execute a non-query statement and return the number of affected rows
	int count = SqlExecutor.execute(conn, "UPDATE " + TABLE_NAME + " set field1 = ? where id = ?", 0, 0);
	log.info("Number of affected rows: {}", count);
	// Execute a non-query statement and return the generated key (if any). If there are multiple generated keys, only the first one is returned.
	Long generatedKey = SqlExecutor.executeForGeneratedKey(conn, "UPDATE " + TABLE_NAME + " set field1 = ? where id = ?", 0, 0);
	log.info("Primary key: {}", generatedKey);

	/* Execute a query statement and return a list of Entity objects. Each Entity object represents a row of data. The Entity object is a HashMap-derived object that stores field names as keys and field values as values. */
	List<Entity> entityList = SqlExecutor.query(conn, "select * from " + TABLE_NAME + " where param1 = ?", new EntityListHandler(), "value");
	log.info("{}", entityList);
} catch (SQLException e) {
	Log.error(log, e, "SQL error!");
} finally {
	DbUtil.close(conn);
}