Package webapp.sql

Source Code of webapp.sql.Sql

package webapp.sql;

import webapp.WebAppException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
* User: gkislin
* Date: 12.05.2014
*/
public class Sql {
    public static ConnectionFactory CONN_FACTORY =
            new DirectConnection();

    private static SqlExecutor<Void> EXECUTOR = new SqlExecutor<Void>() {
        @Override
        public Void execute(PreparedStatement st) throws SQLException {
            st.execute();
            return null;
        }
    };

    public static void execute(String sql) {
        execute(sql, EXECUTOR);
    }

    public static <T> T execute(String sql, SqlExecutor<T> executor) {
        try (Connection conn = CONN_FACTORY.getConnection(); PreparedStatement st = conn.prepareStatement(sql)) {
            T res =  executor.execute(st);
            st.execute();
            return res;
        } catch (SQLException e) {
            throw new WebAppException("Error executing '" + sql + "'", e);
        }
    }

    public static <T> T execute(SqlTransaction<T> executor) {
        try (Connection conn = CONN_FACTORY.getConnection()) {
            try {
                conn.setAutoCommit(false);
                T res = executor.execute(conn);
                conn.commit();
                return res;
            } catch (SQLException e) {
                conn.rollback();
                throw e;
            }
        } catch (SQLException e) {
            throw new WebAppException("Transaction failed", e);
        }
    }
}
TOP

Related Classes of webapp.sql.Sql

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.