当前位置: 首页>>代码示例>>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;未经允许,请勿转载。