Java DataSource execute(DataSource ds, String sql, Object... args)

Here you can find the source of execute(DataSource ds, String sql, Object... args)

Description

execute

License

Apache License

Declaration

public static int execute(DataSource ds, String sql, Object... args) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import java.sql.SQLException;
import java.sql.Statement;

import java.util.Arrays;

import javax.sql.DataSource;

public class Main {

    public static int execute(DataSource ds, String sql, Object... args) {
        if (ds == null || sql == null || sql.trim().length() == 0)
            return 0;

        int result = 0;

        PreparedStatement pstmt = null;
        Connection con = null;//from   w w  w .  j ava 2  s  . c  o  m
        try {
            con = ds.getConnection();
            pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            fillArgs(new Object[][] { args }, pstmt, 0);
            result = pstmt.executeUpdate();
            if (result > 0 && sql.toUpperCase().contains("INSERT INTO")) {
                ResultSet rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    result = rs.getInt(1);
                }
            }
            pstmt.close();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            close(null, pstmt, con);
            System.out.println("---- EWEB4J SQL ----");
            if (args != null && args.length > 0)
                System.out.println("---- " + sql + " " + Arrays.asList(args) + " ----");
            else
                System.out.println("---- " + sql + " ----");
        }

        return result;
    }

    private static void fillArgs(Object[][] args, PreparedStatement pstmt, int i) throws SQLException {
        if (args == null || args.length == 0)
            return;
        if (args[i] == null || args[i].length == 0)
            return;

        for (int j = 0; j < args[i].length; ++j)
            pstmt.setObject(j + 1, args[i][j]);
    }

    public static void close(ResultSet rs, PreparedStatement pstmt, Connection con) {
        try {
            if (rs != null)
                rs.close();
            if (pstmt != null)
                pstmt.close();
            if (con != null)
                con.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

Related

  1. createTableRecommendation(DataSource dataSource)
  2. createTables(DataSource ds)
  3. createTables(final DataSource ds)
  4. doInsert(DataSource ds, String tableName, int id, String value)
  5. doSelect(DataSource ds, String tableName, int id)
  6. execute(String execute, DataSource datasource)
  7. executeQuery(DataSource dataSource, String... queries)
  8. getConnection(CommonDataSource dataSource)
  9. getConnection(DataSource dataSource)