當前位置: 首頁>>代碼示例>>Java>>正文


Java Connection類代碼示例

本文整理匯總了Java中java.sql.Connection的典型用法代碼示例。如果您正苦於以下問題:Java Connection類的具體用法?Java Connection怎麽用?Java Connection使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Connection類屬於java.sql包,在下文中一共展示了Connection類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: updateBorradoTodosProductoPresupuestoDestinatario

import java.sql.Connection; //導入依賴的package包/類
public static boolean updateBorradoTodosProductoPresupuestoDestinatario(ProductoPresupuestoDestinatario destinatarioObjeto, String usuarioResponsable) throws ParseException {
	Connection conect = ConnectionConfiguration.conectar();

	Statement statement = null;
	destinatarioObjeto.changeBorrado();

	String query = "update producto_presupuesto_destinatario set borrado='"	+ destinatarioObjeto.isBorrado() + "', ";
	query += "usuario_responsable='" + usuarioResponsable + "'";

	query += " where nivel =" +destinatarioObjeto.getNivel()+ " and entidad = "+ destinatarioObjeto.getEntidad()+" and tipo_presupuesto = "+destinatarioObjeto.getTipo_presupuesto()+" and programa = "+destinatarioObjeto.getPrograma()+" and subprograma = "+destinatarioObjeto.getSubprograma()+" and proyecto = "+destinatarioObjeto.getProyecto()+" and producto = "+destinatarioObjeto.getProducto();
	try {
		statement = conect.createStatement();
		statement.execute(query);

		conect.close();
		return true;
	} catch (SQLException e) {
		e.printStackTrace();
		return false;
	}

}
 
開發者ID:stppy,項目名稱:spr,代碼行數:23,代碼來源:SqlUpdates.java

示例2: getAccountAssetTransfers

import java.sql.Connection; //導入依賴的package包/類
public static DbIterator<AssetTransfer> getAccountAssetTransfers(long accountId, long assetId, int from, int to) {
    Connection con = null;
    try {
        con = Db.getConnection();
        PreparedStatement pstmt = con.prepareStatement("SELECT * FROM asset_transfer WHERE sender_id = ? AND asset_id = ?"
                + " UNION ALL SELECT * FROM asset_transfer WHERE recipient_id = ? AND sender_id <> ? AND asset_id = ? ORDER BY height DESC"
                + DbUtils.limitsClause(from, to));
        int i = 0;
        pstmt.setLong(++i, accountId);
        pstmt.setLong(++i, assetId);
        pstmt.setLong(++i, accountId);
        pstmt.setLong(++i, accountId);
        pstmt.setLong(++i, assetId);
        DbUtils.setLimits(++i, pstmt, from, to);
        return assetTransferTable.getManyBy(con, pstmt, false);
    } catch (SQLException e) {
        DbUtils.close(con);
        throw new RuntimeException(e.toString(), e);
    }
}
 
開發者ID:muhatzg,項目名稱:burstcoin,代碼行數:21,代碼來源:AssetTransfer.java

示例3: setReorderingWindow

import java.sql.Connection; //導入依賴的package包/類
@Override
public void setReorderingWindow(Connection txn, ContactId c, TransportId t,
		long rotationPeriod, long base, byte[] bitmap) throws DbException {
	PreparedStatement ps = null;
	try {
		String sql = "UPDATE incomingKeys SET base = ?, bitmap = ?"
				+ " WHERE contactId = ? AND transportId = ? AND period = ?";
		ps = txn.prepareStatement(sql);
		ps.setLong(1, base);
		ps.setBytes(2, bitmap);
		ps.setInt(3, c.getInt());
		ps.setString(4, t.getString());
		ps.setLong(5, rotationPeriod);
		int affected = ps.executeUpdate();
		if (affected < 0 || affected > 1) throw new DbStateException();
		ps.close();
	} catch (SQLException e) {
		tryToClose(ps);
		throw new DbException(e);
	}
}
 
開發者ID:rafjordao,項目名稱:Nird2,代碼行數:22,代碼來源:JdbcDatabase.java

示例4: insert

import java.sql.Connection; //導入依賴的package包/類
@Override
public int insert(EventBean data) throws SQLException {
	try (Connection conn = mDataSource.getConnection();
			PreparedStatementHandle prep = (PreparedStatementHandle) conn.prepareStatement("INSERT INTO events "
					+ "(name, description, status, reserved_to_affiliates, reserved_to_partners, minimum_views, minimum_followers) VALUES "
					+ "(?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
		prep.setString(1, data.getName());
		prep.setString(2, data.getDescription());
		prep.setString(3, data.getStatus().name());
		prep.setBoolean(4, data.isReservedToAffiliates());
		prep.setBoolean(5, data.isReservedToPartners());
		prep.setInt(6, data.getMinimumViews());
		prep.setInt(7, data.getMinimumFollowers());
		prep.executeUpdate();
		try (ResultSet rs = prep.getGeneratedKeys()) {
			if (rs.next()) return rs.getInt(1);
			throw new SQLException("Cannot insert element.");
		}
	}
}
 
開發者ID:FightForSub,項目名稱:FFS-Api,代碼行數:21,代碼來源:EventsDao.java

示例5: setQueueId

import java.sql.Connection; //導入依賴的package包/類
@Override
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void setQueueId(Long taskId, String queueId) {
    Connection connection = null;

    try {
        connection = ds.getConnection();

        new H2SqlBuilder().update(connection, Query
                .UPDATE(TABLE.JMD_TASK())
                .SET(JMD_TASK.QUEUE_ID(), queueId)
                .WHERE(JMD_TASK.ID(), Condition.EQUALS, taskId)
        );
    } catch (SQLException e) {
        LOGGER.log(Level.SEVERE, e.toString(), e);
        throw new RuntimeException(e);
    } finally {
        SqlUtil.close(connection);
    }
}
 
開發者ID:jmd-stuff,項目名稱:task-app,代碼行數:21,代碼來源:TaskDaoTestImpl.java

示例6: borradoBeneficiarioTipo

import java.sql.Connection; //導入依賴的package包/類
public static boolean borradoBeneficiarioTipo(BeneficiarioTipo objeto, String usuarioResponsable){
  	 Connection conect=ConnectionConfiguration.conectar();
  	 Statement statement = null;
	 objeto.changeBorrado();
	 	  	 
		 String query = "update beneficiario_tipo set borrado='"+objeto.isBorrado()+"'";
		 		query += ", usuario_responsable='" + usuarioResponsable + "'";
		 
		 query+=" where id ="+objeto.getId(); 
		 try {
			statement=conect.createStatement();
			statement.execute(query);
		    conect.close();
		    return true;
		} catch (SQLException e) {e.printStackTrace(); return false;}
}
 
開發者ID:stppy,項目名稱:tcp,代碼行數:17,代碼來源:SqlUpdates.java

示例7: excuteSqlFromFile

import java.sql.Connection; //導入依賴的package包/類
/**
 * 執行SQL文件
 * 
 * @param conn
 *            數據庫連接
 * @param fileName
 *            文件名
 * @param params
 *            執行參數
 * @throws IOException
 *             IO異常
 * @throws SQLException
 *             SQL異常
 */
private void excuteSqlFromFile(Connection conn, String fileName, Object... params) throws IOException, SQLException {

    // 新建數據庫
    java.net.URL url = this.getClass().getResource(fileName);
    // 從URL對象中獲取路徑信息
    String realPath = url.getPath();

    File file = new File(realPath);
    // 指定文件字符集
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
    String sql = new String();
    String line = new String();
    while ((line = br.readLine()) != (null)) {
        sql += line + "\r\n";
    }
    br.close();
    Statement stmt = conn.createStatement();
    sql = MessageFormat.format(sql, params);
    stmt.execute(sql);
}
 
開發者ID:luckyyeah,項目名稱:YiDu-Novel,代碼行數:35,代碼來源:IndexAction.java

示例8: processWith

import java.sql.Connection; //導入依賴的package包/類
/**
 * @see org.alfasoftware.morf.jdbc.SqlScriptExecutor.QueryBuilder#processWith(org.alfasoftware.morf.jdbc.SqlScriptExecutor.ResultSetProcessor)
 */
@Override
public <T> T processWith(final ResultSetProcessor<T> resultSetProcessor) {
  try {
    final Holder<T> holder = new Holder<>();

    Work work = new Work() {
      @Override
      public void execute(Connection innerConnection) throws SQLException {
        holder.set(executeQuery(query, parameterMetadata, parameterData, innerConnection, resultSetProcessor, maxRows, queryTimeout, standalone));
      }
    };

    if (connection == null) {
      // Get a new connection, and use that...
      doWork(work);
    } else {
      // Get out own connection, and use that...
      work.execute(connection);
    }

    return holder.get();
  } catch (SQLException e) {
    throw new RuntimeSqlException("Error with statement", e);
  }
}
 
開發者ID:alfasoftware,項目名稱:morf,代碼行數:29,代碼來源:SqlScriptExecutor.java

示例9: deleteUnidadResponsable

import java.sql.Connection; //導入依賴的package包/類
public static void deleteUnidadResponsable(String id, String entidad_id, String entidad_nivel_id, String unidad_jerarquica_id){
 	 Connection conect=ConnectionConfiguration.conectar();
 	 Statement statement = null;
 String 							query = "delete from unidad_responsable ";
 //if (id!="")						query+= "id=\""+id+"\", ";
 /*if (nombre!="")					query+= "nombre=\""+nombre+"\", ";
 if (descripcion!="")				query+= "descripcion=\""+descripcion+"\", ";
 if (abrev!="")						query+= "abrev=\""+abrev+"\", ";
 if (numero_fila!="")				query+= "numero_fila=\""+numero_fila+"\", ";
 //if (entidad_id!="")				query+= "entidad_id=\""+entidad_id+"\", ";
 //if (entidad_nivel_id!="")		query+= "entidad_nivel_id=\""+entidad_nivel_id+"\", ";
 //if (unidad_jerarquica_id!="")	query+= "unidad_jerarquica_id=\""+unidad_jerarquica_id+"\", ";
 if (anho!="")						query+= "anho=\""+anho+"\", ";
 query = query.substring(0, query.length()-2);*/
 query+="where id="+id+" and entidad_id="+entidad_id+" and entidad_nivel_id="+entidad_nivel_id+" and unidad_jerarquica_id="+unidad_jerarquica_id;
		
try {
	statement=conect.createStatement();
	statement.execute(query);
    conect.close();
} catch (SQLException e) {e.printStackTrace();}
 }
 
開發者ID:stppy,項目名稱:spr,代碼行數:23,代碼來源:SqlDelete.java

示例10: loadFromDb

import java.sql.Connection; //導入依賴的package包/類
public static MapleRing loadFromDb(int ringId) {
    try {
        MapleRing ret = null;
        Connection con = DatabaseConnection.getConnection(); // Get a connection to the database
        PreparedStatement ps = con.prepareStatement("SELECT * FROM rings WHERE id = ?"); // Get ring details..
        ps.setInt(1, ringId);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            ret = new MapleRing(ringId, rs.getInt("partnerRingId"), rs.getInt("partnerChrId"), rs.getInt("itemid"), rs.getString("partnerName"));
        }
        rs.close();
        ps.close();
        return ret;
    } catch (SQLException ex) {
        ex.printStackTrace();
        return null;
    }
}
 
開發者ID:NovaStory,項目名稱:AeroStory,代碼行數:19,代碼來源:MapleRing.java

示例11: getBanner

import java.sql.Connection; //導入依賴的package包/類
/**
 * Returns a String report for the specified JDBC Connection.
 *
 * For databases with poor JDBC support, you won't get much detail.
 */
public static String getBanner(Connection c) {
    try {
        DatabaseMetaData md = c.getMetaData();
        return (md == null)
                ? null
                : SqltoolRB.jdbc_established.getString(
                        md.getDatabaseProductName(),
                        md.getDatabaseProductVersion(),
                        md.getUserName(),
                                (c.isReadOnly() ? "R/O " : "R/W ")
                                + RCData.tiToString(
                                c.getTransactionIsolation()));
    } catch (SQLException se) {
        return null;
    }
}
 
開發者ID:Julien35,項目名稱:dev-courses,代碼行數:22,代碼來源:SqlFile.java

示例12: addDepart

import java.sql.Connection; //導入依賴的package包/類
public void addDepart(Department depart) {
	// TODO Auto-generated method stub
	Connection con = DBconnection.getConnection();
	PreparedStatement prep = null;	
	try {
		String sql="insert into department(departname,content) values (?,?)";
		prep = con.prepareStatement(sql);
		prep.setString(1, depart.getDepartname());
		prep.setString(2, depart.getContent());
		
		prep.executeUpdate();

	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();

	} finally {
		DBconnection.close(con);
		DBconnection.close(prep);
	}
}
 
開發者ID:liberliushahe,項目名稱:attendance,代碼行數:22,代碼來源:DepartDaoImpl.java

示例13: deleteRobotSettings

import java.sql.Connection; //導入依賴的package包/類
@Override
public void deleteRobotSettings(long botId, long userId, String propKey) {
	if (Preconditions.isEmptyString(propKey)) {
		return;
	}
	String sql = "DELETE FROM " + getTableName() + " WHERE bot_id = ? AND user_id = ? AND prop_key = ?";
	try (
			Connection conn = this.getDataSource().getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			) {
		ps.setLong(1, botId);
		ps.setLong(2, userId);
		ps.setString(3, propKey);
		ps.executeUpdate();
	} catch (SQLException e) {
		getLogger().error(e.getMessage(), e);
	}
}
 
開發者ID:sgr-io,項目名稱:telegram-bot-api,代碼行數:19,代碼來源:MySqlBasedUserSettingsDbWithMultiBotsSupport.java

示例14: doClose

import java.sql.Connection; //導入依賴的package包/類
protected void doClose() {

        try {
            Connection con = getConnection("sa", "password", false);

            if (con != null) {
                Statement stmt = con.createStatement();

                stmt.execute("SHUTDOWN");
                stmt.close();
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        System.exit(0);
    }
 
開發者ID:Julien35,項目名稱:dev-courses,代碼行數:19,代碼來源:TestHarness.java

示例15: getShardCommands

import java.sql.Connection; //導入依賴的package包/類
/**
 * Creates a list of commands to be executed against the shards associated with the connection.
 *
 * @return Pairs of shard locations and associated commands.
 */
private List<Pair<ShardLocation, Statement>> getShardCommands() {
    return this.connection.getShardConnections().stream().map(sc -> {
        try {
            Connection conn = sc.getRight();
            if (conn.isClosed()) {
                // TODO: This hack needs to be perfected. Reopening of connection is not straight forward.
                conn = getConnectionForLocation(sc.getLeft());
            }
            Statement statement = conn.prepareStatement(this.commandText, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            statement.setQueryTimeout(this.getCommandTimeoutPerShard());
            return new ImmutablePair<>(sc.getLeft(), statement);
        }
        catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }).collect(Collectors.toList());
}
 
開發者ID:Microsoft,項目名稱:elastic-db-tools-for-java,代碼行數:23,代碼來源:MultiShardStatement.java


注:本文中的java.sql.Connection類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。