执行非查询 SQL语句

@param sql 需要执行的非查询SQL语句对象(insert/update/delete)

@return 是否执行成功

@throws SQLException SQL执行异常
970381
public boolean execute(Sql sql) throws SQLException {
		
		long start =  System.currentTimeMillis();
		
		if (sql.validate() == false) {
			return false;
		}
		
		boolean result = false;
		
		PreparedStatement stmt = null;
		try {
			stmt = this.createStatment(conn, sql);
			stmt.execute();
			
			result = true;
		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (stmt != null && stmt.isClosed() == false) {
					stmt.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
		
		logger.debug(String.format("Execute %s used %d ms", sql.getSql(), System.currentTimeMillis() - start));

		return result;
	}
691573
@Nullable
    public T query() throws SQLException {
        try (ResultSet r = executeQuery()) {
            if (r.next()) {
                return resultMapper.map(r);
            }
            return null;
        }
    }
511539
@Override
	public final int executeUpdate() throws SQLException {
		Split split = prepare();
		try {
			return stmt.executeUpdate();
		} finally {
			finish(split);
		}
	}
272138
public void runSql( String sql ) throws Exception {
        String[] sqlSplit = sql.split("\n");
        StringBuilder sb = new StringBuilder();
        for( String string : sqlSplit ) {
            String trim = string.trim();
            if (trim.length() == 0) {
                continue;
            }
            if (trim.startsWith("--")) {
                continue;
            }
            sb.append(trim + " ");
        }

        String[] sqls = sb.toString().split(";");
        for( String single : sqls ) {
            executeInsertUpdateDeleteSql(single);
        }
    }
517016
public Stmt prepare( String sql ) throws jsqlite.Exception {
        synchronized (this) {
            Stmt stmt = new Stmt();
            stmt_prepare(sql, stmt);
            return stmt;
        }
    }
671890
public static int execute(Connection conn, String sql, Object... params) throws SQLException {
		PreparedStatement ps = null;
		try {
			ps = StatementUtil.prepareStatement(conn, sql, params);
			return ps.executeUpdate();
		} finally {
			DbUtil.close(ps);
		}
	}
1106856
public static String execQueryAllRows(@NotNull final SQLInputs sqlInputs) throws Exception {
        ConnectionService connectionService = new ConnectionService();
        try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {
            connection.setReadOnly(true);

            Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());

            statement.setQueryTimeout(sqlInputs.getTimeout());
            final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());

            final String resultSetToDelimitedColsAndRows = Format.resultSetToDelimitedColsAndRows(resultSet, sqlInputs.isNetcool(), sqlInputs.getColDelimiter(), sqlInputs.getRowDelimiter());
            if (resultSet != null) {
                resultSet.close();
            }
            return resultSetToDelimitedColsAndRows;
        }
    }
1083069
def _execute(self, sql, args):
        
        sql = sql.lower().strip()
        args = args or ()
        tmp = sql[:6]
        with (yield self._pool.Connection()) as conn:
            try:
                with conn.cursor() as cursor:
                    yield cursor.execute(sql, args=args)
                    if tmp == 'select':
                        datas = cursor.fetchall()   
                        return datas
            except Exception as e:
                err = traceback.format_exc()
                print(err)
                if tmp in ['insert', 'update', 'delete']:
                    yield conn.rollback()
            else:
                if tmp == 'insert':
                    insertId = conn.insert_id()
                    yield conn.commit()
                    # 返回插入的主键id
                    return insertId
                elif tmp in ['update', 'delete']:
                    yield conn.commit()
230698
public SQLException exceptionWithQuery(String sql, SQLException sqlException,
      boolean explicitClosed) {
    if (explicitClosed) {
      return new SQLException(
          "Connection has explicitly been closed/aborted.\nQuery is: " + subQuery(sql),
          sqlException.getSQLState(),
          sqlException.getErrorCode(), sqlException.getCause());
    }

    if (options.dumpQueriesOnException || sqlException.getErrorCode() == 1064) {
      return new SQLException(sqlException.getMessage()
          + "\nQuery is: " + subQuery(sql)
          + "\njava thread: " + Thread.currentThread().getName(),
          sqlException.getSQLState(),
          sqlException.getErrorCode(), sqlException.getCause());
    }
    return sqlException;
  }
565550
protected final <T> T executeQuery(final String sql, final StatementWithReturnBlock<T> queryBlock) throws Exception {
        checkState(initialized);

        setupConnection();
        checkNotNull(connection);
        boolean committed = false;
        try {
            T returnValue = withStatement(connection, sql, queryBlock);
            connection.commit();
            committed = true;
            return returnValue;
        } finally {
            if (!committed) {
                connection.rollback();
                cleanupConnection();
            }
        }
    }
339843
protected void runSQL(String sql) {
		try {
			DataSource dataSource = commerceWarehousePersistence.getDataSource();

			DB db = DBManagerUtil.getDB();

			sql = db.buildSQL(sql);
			sql = PortalUtil.transformSQL(sql);

			SqlUpdate sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(dataSource,
					sql);

			sqlUpdate.update();
		}
		catch (Exception e) {
			throw new SystemException(e);
		}
	}
1239531
public List<Map<String, String>> getMetadataBySql(Sql sql) throws SQLException {
		
		List<Map<String, String>> table = new ArrayList<Map<String, String>>();

		PreparedStatement ps = createStatment(conn, sql);
		ResultSet rs = ps.executeQuery();
		ResultSetMetaData rsme = rs.getMetaData();

		int columnCount = rsme.getColumnCount();
		for (int i = 1; i <= columnCount; i++) {
			
			Map<String, String> field = new HashMap<String, String>();

			field.put("NAME", rsme.getColumnName(i)); // 字段名称
			field.put("TYPE", rsme.getColumnTypeName(i)); //字段类型名称(例如：VACHAR2)
			field.put("SIZE", Integer.toString(rsme.getPrecision(i))); //字段长度
			field.put("NULLABLE", rsme.isNullable(i) == ResultSetMetaData.columnNullable ? "YES" : "NO"); //是否为空
			field.put("REMARK", rsme.getColumnLabel(i)); //字段注释
			
			table.add(field);
		}


		return table;
	}
649516
public static void execute(final Connection connection, final String sql) throws SQLException {
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)){
            preparedStatement.execute();
        }
    }
162023
private PreparedStatement prepareBatchStatement(String sql)
    {
        String sqlCmd = sql.substring(0, 7);

        if (sqlCmd.equals("UPDATE ") || sqlCmd.equals("DELETE ") || (_useBatchInserts && sqlCmd.equals("INSERT ")))
        {
            PreparedStatement stmt = (PreparedStatement) _statements.get(sql);
            if (stmt == null)
            {
                // [olegnitz] for JDK 1.2 we need to list both PreparedStatement and Statement
                // interfaces, otherwise proxy.jar works incorrectly
                stmt = (PreparedStatement) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{
                        PreparedStatement.class, Statement.class, BatchPreparedStatement.class},
                        new PreparedStatementInvocationHandler(this, sql, m_jcd));
                _statements.put(sql, stmt);
            }
            return stmt;
        }
        else
        {
            return null;
        }
    }
836182
public DAO[] executeSelect(String sql, Object[] parameters)
			throws DatabaseException {
		ResultSet rs = executeSelectSQL(sql, parameters, null, false);
		return resultSetToDAO(rs, null);
	}
1186059
WrappedStatement compile(String sql) throws SQLException {
    WrappedStatement ws;
    if (! isEnabled(Option.REUSE_STATEMENTS)) {
      ws = new WrappedStatement(connection.prepareStatement(sql), false);
    }
    else {
      if (pool == null) {
        pool = new IdentityHashMap<>();
      }
      String sqlI = sql.intern();
      ws = pool.get(sqlI);
      if (ws == null) {
        ws =  new WrappedStatement(connection.prepareStatement(sql), true);
        pool.put(sqlI, ws);
      }
    }
    return ws;
  }
567356
public static function execute($conn, $sql) {
    $conn = is_array($conn) ? self::connect($conn) : $conn;
    $result = $conn->query($sql);
    if (!$result) {
      throw new SqlException("Cannot execute $sql: " . $conn->error);
    }

    if ($result && $result !== TRUE) {
      $result->free_result();
    }

  }