微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.sql.Connection的实例源码

项目:spr    文件sqlUpdates.java   
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;
    }

}
项目:burstcoin    文件AssetTransfer.java   
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,assetId);
        dbutils.setLimits(++i,pstmt,from,to);
        return assetTransferTable.getManyBy(con,false);
    } catch (sqlException e) {
        dbutils.close(con);
        throw new RuntimeException(e.toString(),e);
    }
}
项目:Nird2    文件JdbcDatabase.java   
@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);
    }
}
项目:FFS-Api    文件EventsDao.java   
@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.");
        }
    }
}
项目:task-app    文件TaskDaoTestImpl.java   
@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);
    }
}
项目:tcp    文件sqlUpdates.java   
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;}
}
项目:YiDu-Novel    文件IndexAction.java   
/**
 * 执行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);
}
项目:morf    文件sqlScriptExecutor.java   
/**
 * @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);
  }
}
项目:spr    文件sqlDelete.java   
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();}
 }
项目:AeroStory    文件MapleRing.java   
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;
    }
}
项目:dev-courses    文件sqlFile.java   
/**
 * 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;
    }
}
项目:attendance    文件DepartDaoImpl.java   
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);
    }
}
项目:telegram-bot-api    文件MysqlbasedUserSettingsDbWithMultiBotsSupport.java   
@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);
    }
}
项目:dev-courses    文件TestHarness.java   
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);
    }
项目:elastic-db-tools-for-java    文件MultiShardStatement.java   
/**
 * 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());
}
项目:calcite-avatica    文件RemoteDriverTest.java   
@Test public void testTypeInfo() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try {
    final Connection connection = getLocalConnection();
    final ResultSet resultSet =
        connection.getMetaData().getTypeInfo();
    assertTrue(resultSet.next());
    final ResultSetMetaData MetaData = resultSet.getMetaData();
    assertTrue(MetaData.getColumnCount() >= 18);
    assertEquals("TYPE_NAME",MetaData.getColumnName(1));
    assertEquals("DATA_TYPE",MetaData.getColumnName(2));
    assertEquals("PRECISION",MetaData.getColumnName(3));
    assertEquals("sql_DATA_TYPE",MetaData.getColumnName(16));
    assertEquals("sql_DATETIME_SUB",MetaData.getColumnName(17));
    assertEquals("NUM_PREC_RADIX",MetaData.getColumnName(18));
    resultSet.close();
    connection.close();
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
项目:JInsight    文件JDBCInstrumentationTest.java   
@Test
  public void testPreparedStatementExecute() throws Exception {
    long expectedCount = getTimerCount(executeStatementName) + 1;

    Connection connection = datasource.getConnection();
    PreparedStatement preparedStatement = connection.prepareStatement(SELECT_QUERY);

    int rnd = ThreadLocalRandom.current().nextInt(0,presetElements.size());
    String key = presetElementKeys.get(rnd);
    Integer value = presetElements.get(key);

    preparedStatement.setString(1,key);

//    ResultSet resultSet = preparedStatement.executeQuery();
    preparedStatement.execute();
    ResultSet resultSet = preparedStatement.getResultSet();
    resultSet.next();
    assertEquals(value.intValue(),resultSet.getInt(2));
    connection.close();

    assertEquals(expectedCount,getTimerCount(executeStatementName));
  }
项目:Money-Manager    文件ComboBoxList.java   
public int getAdvancedSectorInactiveArraySize() {
    int size = 0;
    String sqlid = "SELECT * \n"
            + "FROM Advanced_Sector_List_Add";

    try (Connection conn = connector();
            Statement stmt = conn.createStatement();
            ResultSet result = stmt.executeQuery(sqlid)) {
            while (result.next()) {
                size = size + 1;
            }
    } catch (Exception e) {
        e.printstacktrace();
    }
    return size;
}
项目:lams    文件DataSourceUtils.java   
/**
 * Actually close the given Connection,obtained from the given DataSource.
 * Same as {@link #releaseConnection},but throwing the original sqlException.
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param con the Connection to close if necessary
 * (if this is {@code null},the call will be ignored)
 * @param dataSource the DataSource that the Connection was obtained from
 * (may be {@code null})
 * @throws sqlException if thrown by JDBC methods
 * @see #doGetConnection
 */
public static void doReleaseConnection(Connection con,DataSource dataSource) throws sqlException {
    if (con == null) {
        return;
    }
    if (dataSource != null) {
        ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
        if (conHolder != null && connectionEquals(conHolder,con)) {
            // It's the transactional Connection: Don't close it.
            conHolder.released();
            return;
        }
    }
    logger.debug("Returning JDBC Connection to DataSource");
    doCloseConnection(con,dataSource);
}
项目:OpenVertretung    文件StatementRegressionTest.java   
/**
 * Tests fix for BUG#28596 - parser in client-side prepared statements runs
 * to end of statement,rather than end-of-line for '#' comments.
 * 
 * Also added support for '--' single-line comments
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug28596() throws Exception {
    String query = "SELECT #\n?,#\n? #?\r\n,-- abcdefg \n?";

    this.pstmt = ((com.MysqL.jdbc.Connection) this.conn).clientPrepareStatement(query);
    this.pstmt.setInt(1,1);
    this.pstmt.setInt(2,2);
    this.pstmt.setInt(3,3);

    assertEquals(3,this.pstmt.getParameterMetaData().getParameterCount());
    this.rs = this.pstmt.executeQuery();

    assertTrue(this.rs.next());

    assertEquals(1,this.rs.getInt(1));
    assertEquals(2,this.rs.getInt(2));
    assertEquals(3,this.rs.getInt(3));
}
项目:OftenPorter    文件DBHandleOnlyTS.java   
@Override
public void close() throws IOException
{
    try
    {
        Connection connection = sqlSession.getConnection();
        if (!connection.getAutoCommit())
        {
            connection.setAutoCommit(true);
        }
    } catch (sqlException e)
    {
        throw new IOException(e);
    }
    sqlSession.close();
}
项目:spanner-jdbc-converter    文件TableDeleter.java   
@Override
protected List<AbstractTablePartWorker> prepareWorkers(Connection source,Connection destination)
        throws sqlException
{
    totalRecordCount = converterUtils.getDestinationRecordCount(destination,table);
    List<AbstractTablePartWorker> workers;
    if (totalRecordCount > 0)
    {
        if (totalRecordCount >= 10000)
        {
            workers = createWorkers(source,destination);
        }
        else
        {
            workers = new ArrayList<>(1);
            workers.add(new SingleDeleteWorker(config,table,totalRecordCount));
        }
    }
    else
    {
        workers = Collections.emptyList();
    }

    return workers;
}
项目:java-course    文件sqlDao.java   
/**
 * {@inheritDoc}
 */
@Override
public Integer getoptionVotes(long pollID,long optionID) {
    Integer data = null;
    Connection con = sqlConnectionProvider.getConnection();
    try (PreparedStatement pst = con
            .prepareStatement("SELECT VotesCount FROM PollOptions WHERE pollID=? AND id=?")) {
        pst.setLong(1,Long.valueOf(pollID));
        pst.setLong(2,optionID);
        try (ResultSet rs = pst.executeQuery()) {
            while (rs != null && rs.next()) {
                data = Integer.valueOf(rs.getInt(1));
            }
        }
    } catch (Exception ex) {
        throw new DAOException(
                "Unable to get Votes from poll options table.",ex);
    }
    return data;
}
项目:Lucid2.0    文件MapleClient.java   
public boolean gainCharacterSlot() {
    if (getCharacterSlots() >= 15) {
        return false;
    }
    charslots++;
    try {
        Connection con = DatabaseConnection.getConnection();
        try (PreparedStatement ps = con
                .prepareStatement("UPDATE character_slots SET charslots = ? WHERE worldid = ? AND accid = ?")) {
            ps.setInt(1,charslots);
            ps.setInt(2,world);
            ps.setInt(3,accId);
            ps.executeUpdate();
            ps.close();
        }
    } catch (sqlException sqlE) {
        return false;
    }
    return true;
}
项目:hotelbook-JavaWeb    文件LoginDao.java   
@Override
public int queryDatanum() throws sqlException {

    Connection conn = DBUtil.getConnection();

    String sql = "select count(*) from login;";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    ResultSet rs = pstmt.executeQuery();

    int num;
    if (rs.next()) num = rs.getInt("count(*)");
    else num = 0;

    rs.close();
    pstmt.close();

    return num;
}
项目:taskana    文件TaskanaProducersTest.java   
@Test
public void testCommit() throws sqlException,ClassNotFoundException,NamingException {

    Client client = ClientBuilder.newClient();
    client.target("http://127.0.0.1:8090/rest/test").request().get();

    Class.forName("org.h2.Driver");
    int resultCount = 0;
    try (Connection conn = DriverManager.getConnection("jdbc:h2:~/data/testdb;AUTO_SERVER=TRUE","SA","SA")) {
        ResultSet rs = conn.createStatement().executeQuery("SELECT ID,OWNER FROM TASK");

        while (rs.next()) {
            resultCount++;
        }
    }

    Assert.assertEquals(1,resultCount);
}
项目:lj-line-bot    文件MainDao.java   
public static void CreateTableData(String groupId){
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try{
        connection = DbConnection.getConnection();
        preparedStatement = connection.prepareStatement(
                "CREATE TABLE IF NOT EXISTS " + groupId +
                        "(" +
                        id + " TEXT PRIMARY KEY," +
                        deskripsi + " TEXT NOT NULL," +
                        tipe + " " +tipe_data + " NOT NULL" +
                        ")"
        );
        if (preparedStatement.executeUpdate()==1)
            System.out.println("Create table " + groupId + "berhasil");
    } catch (Exception ex){
        System.out.println("Gagal create table " + groupId + " : " + ex.toString());
    } finally {
        DbConnection.ClosePreparedStatement(preparedStatement);
        DbConnection.CloseConnection(connection);
    }
}
项目:L2jBrasil    文件L2Clan.java   
/**
 * @return Returns the clan notice.
 */
public String getNotice()
{
 Connection con = null;
 try
 {
     con = L2DatabaseFactory.getInstance().getConnection();
     PreparedStatement statement = con.prepareStatement("SELECT notice FROM clan_notices WHERE clanID=?");
     statement.setInt(1,getClanId());
     ResultSet rset = statement.executeQuery();

     while (rset.next())
     {
         _notice = rset.getString("notice");
     }

     rset.close();
     statement.close();
     con.close();

 } catch (Exception e)
 {
     if (Config.DEBUG)
     System.out.println("BBS: Error while getting notice from DB for clan "+ this.getClanId() + "");
     if(e.getMessage()!=null)
         if (Config.DEBUG)
         System.out.println("BBS: Exception = "+e.getMessage()+"");
 }
 return _notice;
}
项目:snu-artoon    文件MetadataManager.java   
/**
 * Insert new chapter to the given webtoon,and image database for that chapter.
 * @param webtoonName webtoon name
 * @param authorName author name
 * @param chapterNumber new chapter number
 * @param chapterName new chapter name
 * @param uploadedDate new uploaded date
 * @param likeNumber number of likes
 * @param dislikeNumber number of dislikes
 * @param thumbnailImage filename of thumbnail images
 */
public static void insertNewChapter(String webtoonName,String authorName,String chapterNumber,String chapterName,String uploadedDate,int likeNumber,int dislikeNumber,String thumbnailImage) {
    String url = "jdbc:sqlite:Metadata";

    try {
        // Open sql
        Connection connection = DriverManager.getConnection(url);
        Statement statement = connection.createStatement();

        String webtoonHashID = HashManager.md5(webtoonName + "_" + authorName);

        // insert chapter sql
        String sql = "INSERT INTO ChapterListDB_" + webtoonHashID +  " VALUES('"
                + chapterNumber + "','" + chapterName + "','" + uploadedDate + "',"
                + likeNumber + "," + dislikeNumber + ",'" + thumbnailImage + "');";
        statement.execute(sql);

        // create ImageListDB table sql
        String chapterHashID = HashManager.md5(chapterNumber + "_" + chapterName);
        sql = "CREATE TABLE ImageListDB_" + webtoonHashID + "_" + chapterHashID
                + "(Image TEXT);";
        statement.execute(sql);
    } catch (sqlException e) {
        e.printstacktrace();
    }
}
项目:Money-Manager    文件Source.java   
public void deleteSource(String sourceName) {
    String delete = "DELETE FROM Source_List WHERE sourceList = ?";

    try (Connection conn = connector();
            PreparedStatement pstmt = conn.prepareStatement(delete)){
        pstmt.setString(1,sourceName);
        pstmt.executeUpdate();
    } catch (Exception e) {
        e.printstacktrace();
    }

}
项目:otus_java_2017_04    文件Main.java   
public static void main(String[] args) {
    //ConnectionFactory connectionFactory = new JDBCConnectionFactory();
    ConnectionFactory connectionFactory = new MyPoolConnectionFactory(new JDBCConnectionFactory());

    try (Connection connection = connectionFactory.get()) {
        System.out.println("Connected to: " + connection.getMetaData().getURL());
        System.out.println("DB name: " + connection.getMetaData().getDatabaseProductName());
        System.out.println("DB version: " + connection.getMetaData().getDatabaseProductVersion());
        System.out.println("Driver: " + connection.getMetaData().getDriverName());
    } catch (sqlException e) {
        e.printstacktrace();
    }

    connectionFactory.dispose();
}
项目:ats-framework    文件sqlServerDbReadAccess.java   
@Override
public List<ScenarioMetaInfo> getScenarioMetaInfo( int scenarioId ) throws DatabaseAccessException {

    List<ScenarioMetaInfo> scenarioMetaInfoList = new ArrayList<>();
    Connection connection = getConnection();
    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
        statement = connection.prepareStatement("SELECT * FROM tScenarioMetainfo WHERE scenarioId = " + scenarioId);
        rs = statement.executeQuery();
        while (rs.next()) {
            ScenarioMetaInfo runMetainfo = new ScenarioMetaInfo();
            runMetainfo.MetaInfoId = rs.getInt("MetaInfoId");
            runMetainfo.scenarioId = rs.getInt("scenarioId");
            runMetainfo.name = rs.getString("name");
            runMetainfo.value = rs.getString("value");
            scenarioMetaInfoList.add(runMetainfo);
        }
    } catch (Exception e) {
        throw new DatabaseAccessException("Error retrieving scenario Metainfo for scenario with id '" + scenarioId
                                          + "'",e);
    } finally {
        dbutils.closeResultSet(rs);
        dbutils.close(connection,statement);
    }

    return scenarioMetaInfoList;
}
项目:server-utility    文件Context.java   
/**
 * Close connection.
 *
 * @param connection
 *            the connection
 */
private void closeConnection(Connection connection) {
    if (connection != null) {
        try {
            connection.close();
        } catch (sqlException e) {
            // ignore
        }
    }
}
项目:morf    文件TestsqlServerDialect.java   
/**
 * @see org.alfasoftware.morf.jdbc.AbstractsqlDialectTest#verifyPostInsertStatementsInsertingUnderAutonumLimit(org.alfasoftware.morf.jdbc.sqlScriptExecutor,com.MysqL.jdbc.Connection)
 */
@Override
protected void verifyPostInsertStatementsInsertingUnderAutonumLimit(sqlScriptExecutor sqlScriptExecutor,Connection connection) {
  verify(sqlScriptExecutor).execute(listCaptor.capture(),eq(connection));
  verifyPostInsertStatements(listCaptor.getValue());
  verifyNoMoreInteractions(sqlScriptExecutor);
}
项目:ProyectoPacientes    文件ConnectionRegressionTest.java   
/**
 * Tests fix for Bug#16634180 - LOCK WAIT TIMEOUT EXCEEDED CAUSES sqlEXCEPTION,SHOULD CAUSE sqlTRANSIENTEXCEPTION
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug16634180() throws Exception {

    if (Util.isJdbc4()) {
        // relevant JDBC4+ test is testsuite.regression.jdbc4.ConnectionRegressionTest.testBug16634180()
        return;
    }

    createTable("testBug16634180","(pk integer primary key,val integer)","InnoDB");
    this.stmt.executeUpdate("insert into testBug16634180 values(0,0)");

    Connection c1 = null;
    Connection c2 = null;

    try {
        c1 = getConnectionWithProps(new Properties());
        c1.setAutoCommit(false);
        Statement s1 = c1.createStatement();
        s1.executeUpdate("update testBug16634180 set val=val+1 where pk=0");

        c2 = getConnectionWithProps(new Properties());
        c2.setAutoCommit(false);
        Statement s2 = c2.createStatement();
        try {
            s2.executeUpdate("update testBug16634180 set val=val+1 where pk=0");
            fail("ER_LOCK_WAIT_TIMEOUT should be thrown.");
        } catch (MysqLTransientException ex) {
            assertEquals(MysqLErrorNumbers.ER_LOCK_WAIT_TIMEOUT,ex.getErrorCode());
            assertEquals(sqlError.sql_STATE_ROLLBACK_SERIALIZATION_FAILURE,ex.getsqlState());
            assertEquals("Lock wait timeout exceeded; try restarting transaction",ex.getMessage());
        }
    } finally {
        if (c1 != null) {
            c1.close();
        }
        if (c2 != null) {
            c2.close();
        }
    }
}
项目:plugin-bt-jira    文件AbstractJiraUploadTest.java   
/**
 * Clean data base with 'MDA' JIRA project.
 */
@AfterClass
public static void cleanJiraDataBaseForImport() throws sqlException {
    final DataSource datasource = new SimpleDriverDataSource(new JDBCDriver(),"jdbc:hsqldb:mem:dataSource",null,null);
    final Connection connection = datasource.getConnection();

    try {
        ScriptUtils.executesqlScript(connection,new EncodedResource(new ClassPathResource("sql/upload/jira-drop.sql"),StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:Spring-Security-Third-Edition    文件JdbcEventDao.java   
@Override
public int createEvent(final Event event) {
    if (event == null) {
        throw new IllegalArgumentException("event cannot be null");
    }
    if (event.getId() != null) {
        throw new IllegalArgumentException("event.getId() must be null when creating a new Message");
    }
    final CalendarUser owner = event.getowner();
    if (owner == null) {
        throw new IllegalArgumentException("event.getowner() cannot be null");
    }
    final CalendarUser attendee = event.getAttendee();
    if (attendee == null) {
        throw new IllegalArgumentException("attendee.getowner() cannot be null");
    }
    final Calendar when = event.getWhen();
    if(when == null) {
        throw new IllegalArgumentException("event.getWhen() cannot be null");
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcoperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws sqlException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into events (when,summary,owner,attendee) values (?,new String[] { "id" });
            ps.setDate(1,new java.sql.Date(when.getTimeInMillis()));
            ps.setString(2,event.getSummary());
            ps.setString(3,event.getDescription());
            ps.setInt(4,owner.getId());
            ps.setobject(5,attendee == null ? null : attendee.getId());
            return ps;
        }
    },keyHolder);
    return keyHolder.getKey().intValue();
}
项目:helpdesk    文件DatabaseInitiationService.java   
void createDBThenInit() throws Exception {
    Configurator cfg = ConfiguratorFactory.getDefaultInstance();
    String propCreate = cfg.getProperty("create","false");
    cfg.setProperty("create","true");
    Connection connection = ConnectionManager.getConnection(cfg);
    //create db success;
    //do DDL create table
    Statement stats = connection.createStatement();

    String[] ddls = {
        "CREATE TABLE ITEMS(\r\n" + 
        "ID BIGINT PRIMARY KEY,\r\n" + 
        "NAME VARCHAR(128),\r\n" + 
        "DESCRIPTION VARCHAR(512),\r\n" + 
        "TYPE SMALLINT,\r\n" + 
        "CONTENT CLOB,\r\n" + 
        "READ_COUNT SMALLINT,\r\n" + 
        "CREATE_TIME TIMESTAMP,\r\n" + 
        "UPDATE_TIME TIMESTAMP,\r\n" + 
        "PARENT BIGINT\r\n" + 
        ")","CREATE TABLE TAGS(\r\n" + 
        "ID BIGINT PRIMARY KEY,\r\n" + 
        "CREATE_TIME TIMESTAMP\r\n" + 
        ")"
    };
    for(String sql:ddls) {
        stats.addBatch(sql);
    }
    int[] rsts = stats.executeBatch();
    for(int i=0;i<rsts.length;i++) {
        ProcessLogger.debug("Executed {0} DDL result:{1}",i,rsts[i]);
    }
    cfg.setProperty("create",propCreate);
}
项目:OpenVertretung    文件ConnectionRegressionTest.java   
/**
 * Tests fix for BUG#36948 - Trying to use trustCertificateKeyStoreUrl
 * causes an IllegalStateException.
 * 
 * Requires test certificates from testsuite/ssl-test-certs to be installed
 * on the server being tested.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug36948() throws Exception {
    Connection _conn = null;

    try {
        Properties props = getPropertiesFromTestsuiteUrl();
        String host = props.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY,"localhost");
        String port = props.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY,"3306");
        String db = props.getProperty(NonRegisteringDriver.dbnAME_PROPERTY_KEY,"test");

        String hostSpec = host;

        if (!NonRegisteringDriver.isHostPropertiesList(host)) {
            hostSpec = host + ":" + port;
        }

        props = getHostFreePropertiesFromTestsuiteUrl();
        props.remove("useSSL");
        props.remove("requireSSL");
        props.remove("verifyServerCertificate");
        props.remove("trustCertificateKeyStoreUrl");
        props.remove("trustCertificateKeyStoreType");
        props.remove("trustCertificateKeyStorePassword");

        final String url = "jdbc:MysqL://" + hostSpec + "/" + db + "?useSSL=true&requireSSL=true&verifyServerCertificate=true"
                + "&trustCertificateKeyStoreUrl=file:src/testsuite/ssl-test-certs/ca-truststore&trustCertificateKeyStoreType=JKS"
                + "&trustCertificateKeyStorePassword=password";

        _conn = DriverManager.getConnection(url,props);
    } finally {
        if (_conn != null) {
            _conn.close();
        }
    }

}
项目:slardar    文件DBCPool.java   
public DBCPool(int maxPoolSize,int maxIdle,int minIdle,long keepAliveTime,Queue queue) {
    PoolConfig.config(maxPoolSize,maxIdle,minIdle,keepAliveTime);
    this.maxPoolSize = maxPoolSize;
    this.maxIdle = maxIdle;
    this.minIdle = minIdle;
    this.keepAliveTime = keepAliveTime;
    conpool = new ConcurrentLinkedQueue<Connection>();
    idleQueue = queue;
    initQueue();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。