类java.sql.DriverManager源码实例Demo

下面列出了怎么用java.sql.DriverManager的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: tp_java_2015_02   文件: SimpleExample.java
public static Connection getConnection() {
	try{
		DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());
		
		StringBuilder url = new StringBuilder();
		
		url.
		append("jdbc:mysql://").		//db type
		append("localhost:"). 			//host name
		append("3306/").				//port
		append("db_example?").			//db name
		append("user=tully&").			//login
		append("password=tully");		//password
		
		System.out.append("URL: " + url + "\n");
		
		Connection connection = DriverManager.getConnection(url.toString());
		return connection;
	} catch (SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e) {
		e.printStackTrace();
	}
       return null;
}
 
源代码2 项目: phoenix   文件: DistinctCountIT.java
@Test
public void testDistinctCountLimitBug5217() throws Exception {
    Connection conn = null;
    try {
        Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
        conn = DriverManager.getConnection(getUrl(), props);
        String tableName = generateUniqueName();
        String sql = "create table " + tableName + "( "+
                " pk1 integer not null , " +
                " pk2 integer not null, " +
                " v integer, " +
                " CONSTRAINT TEST_PK PRIMARY KEY (pk1,pk2))";
        conn.createStatement().execute(sql);
        conn.createStatement().execute("UPSERT INTO "+tableName+"(pk1,pk2,v) VALUES (1,1,1)");
        conn.createStatement().execute("UPSERT INTO "+tableName+"(pk1,pk2,v) VALUES (2,2,2)");
        conn.commit();

        sql = "select count(distinct pk1) from " + tableName + " limit 1";
        ResultSet rs = conn.prepareStatement(sql).executeQuery();
        assertResultSet(rs, new Object[][]{{Long.valueOf(2L)}});
    } finally {
        if(conn!=null) {
            conn.close();
        }
    }
}
 
源代码3 项目: Tomcat8-Source-Read   文件: TestSlowQueryReport.java
@Before
public void setUp() throws SQLException {
    DriverManager.registerDriver(new MockDriver());

    // use our mock driver
    this.datasource.setDriverClassName(MockDriver.class.getName());
    this.datasource.setUrl(MockDriver.url);

    // Required to trigger validation query's execution
    this.datasource.setInitialSize(1);
    this.datasource.setTestOnBorrow(true);
    this.datasource.setValidationInterval(-1);
    this.datasource.setValidationQuery("SELECT 1");
    this.datasource.setMaxActive(1);
    this.datasource.setJdbcInterceptors(SlowQueryReportJmx.class.getName()+"(threshold=50,notifyPool=false)");
}
 
源代码4 项目: lutece-core   文件: ConnectionPool.java
/**
 * Creates a new connection. <br>
 * The connection is wrapped by {@link LuteceConnection}
 *
 * @return The new created connection
 * @throws SQLException
 *             The SQL exception
 */
private Connection newConnection( ) throws SQLException
{
    Connection conn;

    if ( _strUser == null )
    {
        conn = DriverManager.getConnection( _strUrl );
    }
    else
    {
        conn = DriverManager.getConnection( _strUrl, _strUser, _strPassword );
    }

    // wrap connection so this connection pool is used when conn.close() is called
    conn = LuteceConnectionFactory.newInstance( this, conn );

    _logger.info( "New connection created. Connections count is : " + ( getConnectionCount( ) + 1 ) );

    return conn;
}
 
源代码5 项目: phoenix   文件: ArithmeticQueryIT.java
@Test
public void testOrderOfOperationsAdditionDivision() throws Exception {
    Connection conn = DriverManager.getConnection(getUrl());
    initIntegerTable(conn);
    ResultSet rs;
    
    // 6 + 4 / 3
    // 6 + 1
    // 7
    rs = conn.createStatement().executeQuery("SELECT six + four / three FROM ARITHMETIC_TEST");
    assertTrue(rs.next());
    assertEquals(7, rs.getLong(1));
    assertFalse(rs.next());
    
    // 4 / 3 + 6
    // 1 + 6     
    // 7
    rs = conn.createStatement().executeQuery("SELECT four / three + six FROM ARITHMETIC_TEST");
    assertTrue(rs.next());
    assertEquals(7, rs.getLong(1));
    assertFalse(rs.next());
}
 
源代码6 项目: metadata   文件: ScriptRunnerTest.java
@Test
    public void sqlServerTest() throws SQLException, IOException {
        final String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test";
        final String username = "sa";
        final String password = "hydb001*";
        Connection conn = DriverManager.getConnection(url, username, password);
        ScriptRunner runner = new ScriptRunner(conn);
        Resources.setCharset(Charset.forName("UTF-8")); //设置字符集,不然中文乱码插入错误
        runner.setLogWriter(null);//设置是否输出日志

        final File file  = new File("D:\\CODE\\metadata\\metadata-core\\src\\main\\resources\\coreSqlServer.sql");
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
        runner.runScript(isr);
//        runner.runScript(Resources.getResourceAsReader("sql/CC21-01.sql"));
        runner.closeConnection();
        conn.close();
    }
 
源代码7 项目: Mycat2   文件: MigrateUtils.java
public static void execulteSql(String sql, String toDn) throws SQLException, IOException {
    PhysicalDBNode dbNode = MycatServer.getInstance().getConfig().getDataNodes().get(toDn);
    PhysicalDBPool dbPool = dbNode.getDbPool();
    PhysicalDatasource datasource = dbPool.getSources()[dbPool.getActivedIndex()];
    DBHostConfig config = datasource.getConfig();
    Connection con = null;
    try {
        con = DriverManager
                .getConnection("jdbc:mysql://" + config.getUrl() + "/" + dbNode.getDatabase(), config.getUser(), config.getPassword());

        JdbcUtils.execute(con, sql, new ArrayList<>());

    } finally {
        JdbcUtils.close(con);
    }

}
 
源代码8 项目: phoenix   文件: QueryTest.java
@Test
public void testDateInList() throws Exception {
    String query = "SELECT entity_id FROM ATABLE WHERE a_date IN (?,?) AND a_integer < 4";
    String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
    Properties props = new Properties(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(url, props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setDate(1, new Date(0));
        statement.setDate(2, date);
        ResultSet rs = statement.executeQuery();
        assertTrue(rs.next());
        assertEquals(ROW1, rs.getString(1));
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
源代码9 项目: ShoppingCartinJava   文件: KidsDB.java
public static ArrayList<ProductList> TableGenerator(){
        ArrayList<ProductList> list = new ArrayList<>();
        try {
            Connection con = DriverManager.getConnection("jdbc:sqlite:DBs/kidsDB.db");
            Statement ps = con.createStatement();
            ResultSet rs = ps.executeQuery("SELECT mbrand, mmodel, mprice,mquantity, mdescription, mphoto FROM kids");
            
            ProductList pl;
            
            while(rs.next()){
                pl = new ProductList(rs.getString("mbrand"),rs.getString("mmodel"),
                        rs.getInt("mprice"),rs.getInt("mquantity"),rs.getString("mdescription"),
                        rs.getString("mphoto"));
                
                list.add(pl);

            }
            
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(MobileDB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return list;
}
 
源代码10 项目: Komondor   文件: ConnectionTest.java
/**
 * Test for Driver.connect() behavior clarifications:
 * - connect() throws SQLException if URL is null.
 */
public void testDriverConnectNullArgument() throws Exception {
    assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
        public Void call() throws Exception {
            Driver mysqlDriver = new Driver();
            mysqlDriver.connect(null, null);
            return null;
        }
    });

    assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
        public Void call() throws Exception {
            DriverManager.getConnection(null);
            return null;
        }
    });
}
 
源代码11 项目: incubator-iotdb   文件: IoTDBMultiSeriesIT.java
@Test
public void selectUnknownTimeSeries() throws ClassNotFoundException {
  Class.forName(Config.JDBC_DRIVER_NAME);

  try (Connection connection = DriverManager
      .getConnection(Config.IOTDB_URL_PREFIX + "127.0.0.1:6667/", "root", "root");
      Statement statement = connection.createStatement()) {
    statement.execute("select s0, s10 from root.vehicle.*");
    try (ResultSet resultSet = statement.getResultSet()) {
      int cnt = 0;
      while (resultSet.next()) {
        cnt++;
      }
      assertEquals(23400, cnt);
    }
  } catch (SQLException e) {
    e.printStackTrace();
    fail();
  }
}
 
源代码12 项目: flink   文件: JdbcTableSourceITCase.java
@Before
public void before() throws ClassNotFoundException, SQLException {
	System.setProperty("derby.stream.error.field", JdbcTestBase.class.getCanonicalName() + ".DEV_NULL");
	Class.forName(DRIVER_CLASS);

	try (
		Connection conn = DriverManager.getConnection(DB_URL + ";create=true");
		Statement statement = conn.createStatement()) {
		statement.executeUpdate("CREATE TABLE " + INPUT_TABLE + " (" +
				"id BIGINT NOT NULL," +
				"timestamp6_col TIMESTAMP, " +
				"timestamp9_col TIMESTAMP, " +
				"time_col TIME, " +
				"real_col FLOAT(23), " +    // A precision of 23 or less makes FLOAT equivalent to REAL.
				"double_col FLOAT(24)," +   // A precision of 24 or greater makes FLOAT equivalent to DOUBLE PRECISION.
				"decimal_col DECIMAL(10, 4))");
		statement.executeUpdate("INSERT INTO " + INPUT_TABLE + " VALUES (" +
				"1, TIMESTAMP('2020-01-01 15:35:00.123456'), TIMESTAMP('2020-01-01 15:35:00.123456789'), " +
				"TIME('15:35:00'), 1.175E-37, 1.79769E+308, 100.1234)");
		statement.executeUpdate("INSERT INTO " + INPUT_TABLE + " VALUES (" +
				"2, TIMESTAMP('2020-01-01 15:36:01.123456'), TIMESTAMP('2020-01-01 15:36:01.123456789'), " +
				"TIME('15:36:01'), -1.175E-37, -1.79769E+308, 101.1234)");
	}
}
 
源代码13 项目: phoenix   文件: ArithmeticQueryTest.java
@Test
public void testSumUnsignedDouble() throws Exception {
    initSumDoubleValues(null);
    String query = "SELECT SUM(ud) FROM SumDoubleTest";
    Properties props = new Properties(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertTrue(Doubles.compare(rs.getDouble(1), 0.015)==0);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
源代码14 项目: kareldb   文件: RemoteClusterHttpAuthTestHarness.java
protected void readWriteData(String url, String tableName, Properties props) throws Exception {
    try (Connection conn = DriverManager.getConnection(url, props);
         Statement stmt = conn.createStatement()) {
        assertFalse(stmt.execute("DROP TABLE IF EXISTS " + tableName));
        assertFalse(stmt.execute("CREATE TABLE " + tableName + " (pk integer, msg varchar(10))"));

        assertEquals(1, stmt.executeUpdate("INSERT INTO " + tableName + " VALUES(1, 'abcd')"));
        assertEquals(1, stmt.executeUpdate("INSERT INTO " + tableName + " VALUES(2, 'bcde')"));
        assertEquals(1, stmt.executeUpdate("INSERT INTO " + tableName + " VALUES(3, 'cdef')"));

        ResultSet results = stmt.executeQuery("SELECT count(1) FROM " + tableName);
        assertNotNull(results);
        assertTrue(results.next());
        assertEquals(3, results.getInt(1));
    }
}
 
源代码15 项目: lucene-solr   文件: JdbcTest.java
@Ignore("Fix error checking")
@Test
@SuppressWarnings({"try"})
public void testErrorPropagation() throws Exception {
  //Test error propagation
  Properties props = new Properties();
  props.put("aggregationMode", "facet");
  try (Connection con = DriverManager.getConnection("jdbc:solr://" + zkHost + "?collection=" + COLLECTIONORALIAS, props)) {
    try (Statement stmt = con.createStatement()) {
      try (ResultSet rs = stmt.executeQuery("select crap from " + COLLECTIONORALIAS + " group by a_s " +
          "order by sum(a_f) desc")) {
      } catch (Exception e) {
        String errorMessage = e.getMessage();
        assertTrue(errorMessage.contains("Group by queries must include at least one aggregate function"));
      }
    }
  }
}
 
源代码16 项目: gemfirexd-oss   文件: GFEDBManager.java
public static Connection getReadCommittedConnection() throws SQLException {
  
  Connection conn = null;
  if (SQLTest.hasJSON) {
    Properties info = new Properties();
    info.setProperty("sync-commits", "true");
    conn = DriverManager.getConnection(protocol + dbName, info);
  }
  else {
    conn = DriverManager.getConnection(protocol + dbName);
  }
  if (SQLTest.random.nextInt(20) == 1) {
  	//test auto upgrade to read committed
  	conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
  } else {
    conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
  }
  conn.setAutoCommit(false); 
  return conn;
}
 
源代码17 项目: phoenix   文件: NotQueryIT.java
@Test
public void testNotEquals2() throws Exception {
    String query = "SELECT entity_id FROM // one more comment  \n" +
    "aTable WHERE organization_id=? and not a_integer = 1 and a_integer <= 2";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 2
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertEquals(rs.getString(1), ROW2);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
源代码18 项目: mysql_perf_analyzer   文件: ConnectionFactory.java
public static Connection connect(DBInstanceInfo db, String username, String password, MyPerfContext context)
 throws java.sql.SQLException
 {
java.util.Properties info = new java.util.Properties();
info.put ("user", username);
info.put ("password",password);
if("oracle".equalsIgnoreCase(db.getDbType()))
{
  info.put("oracle.net.CONNECT_TIMEOUT", String.valueOf(context.getConnectionTimeout()));
  info.put("oracle.net.READ_TIMEOUT", String.valueOf(context.getConnectionReadTimeout()));
  info.put("oracle.jdbc.ReadTimeout", String.valueOf(context.getConnectionReadTimeout()));
}
else if("mysql".equalsIgnoreCase(db.getDbType()))		
{
  info.put("connectTimeout", String.valueOf(context.getConnectionTimeout()));
  info.put("socketTimeout", String.valueOf(context.getConnectionReadTimeout()));
}
return DriverManager.getConnection(db.getConnectionString(), info);
 }
 
源代码19 项目: phoenix   文件: GlobalIndexOptimizationIT.java
private void testOptimizationTenantSpecific(String dataTableName, String indexTableName, Integer saltBuckets) throws Exception {
    createBaseTable(dataTableName, saltBuckets, "('e','i','o')", true);
    Connection conn1 = DriverManager.getConnection(getUrl() + ';' + PhoenixRuntime.TENANT_ID_ATTRIB + "=tid1");
    try{
        conn1.createStatement().execute("UPSERT INTO " + dataTableName + " values(1,2,4,'z')");
        conn1.createStatement().execute("UPSERT INTO " + dataTableName + " values(1,2,3,'a')");
        conn1.createStatement().execute("UPSERT INTO " + dataTableName + " values(2,4,2,'a')");
        conn1.createStatement().execute("UPSERT INTO " + dataTableName + " values(3,1,1,'c')");
        conn1.commit();
        createIndex(indexTableName, dataTableName, "v1");
        
        String query = "SELECT /*+ INDEX(" + dataTableName + " " + indexTableName + ")*/ k1,k2,k3,v1 FROM " + dataTableName +" where v1='a'";
        ResultSet rs = conn1.createStatement().executeQuery("EXPLAIN "+ query);
        
        String actual = QueryUtil.getExplainPlan(rs);
        String expected = "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + dataTableName + " \\['tid1'\\]\n" +
                        "    SKIP-SCAN-JOIN TABLE 0\n" +
                        "        CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexTableName + " \\['tid1','a'\\]\n" +
                        "            SERVER FILTER BY FIRST KEY ONLY\n" +
                        "    DYNAMIC SERVER FILTER BY \\(\"" + dataTableName + ".K1\", \"" + dataTableName + ".K2\"\\) IN \\(\\(\\$\\d+.\\$\\d+, \\$\\d+.\\$\\d+\\)\\)";
        assertTrue("Expected:\n" + expected + "\ndid not match\n" + actual, Pattern.matches(expected, actual));
        
        rs = conn1.createStatement().executeQuery(query);
        assertTrue(rs.next());
        assertEquals(1, rs.getInt("k1"));
        assertEquals(2, rs.getInt("k2"));
        assertEquals(3, rs.getInt("k3"));
        assertEquals("a", rs.getString("v1"));
        assertTrue(rs.next());
        assertEquals(2, rs.getInt("k1"));
        assertEquals(4, rs.getInt("k2"));
        assertEquals(2, rs.getInt("k3"));
        assertEquals("a", rs.getString("v1"));
        assertFalse(rs.next());
    } finally {
        conn1.close();
    }
}
 
源代码20 项目: phoenix   文件: FirstValuesFunctionIT.java
public void rowLessThanOffsetWithGroupBy() throws Exception {
    Connection conn = DriverManager.getConnection(getUrl());

    String tableName = generateUniqueName();
    String ddl = "CREATE TABLE IF NOT EXISTS " + tableName + " "
            + "(id INTEGER NOT NULL PRIMARY KEY, page_id UNSIGNED_LONG,"
            + " dates INTEGER, val INTEGER)";
    conn.createStatement().execute(ddl);

    conn.createStatement().execute(
        "UPSERT INTO " + tableName + " (id, page_id, dates, val) VALUES (2, 8, 0, 7)");
    conn.createStatement().execute(
        "UPSERT INTO " + tableName + " (id, page_id, dates, val) VALUES (3, 8, 1, 9)");
    conn.createStatement().execute(
        "UPSERT INTO " + tableName + " (id, page_id, dates, val) VALUES (4, 8, 2, 4)");
    conn.createStatement().execute(
        "UPSERT INTO " + tableName + " (id, page_id, dates, val) VALUES (5, 8, 2, 2)");
    conn.createStatement().execute(
        "UPSERT INTO " + tableName + " (id, page_id, dates, val) VALUES (6, 8, 3, 3)");
    conn.createStatement().execute(
        "UPSERT INTO " + tableName + " (id, page_id, dates, val) VALUES (7, 9, 3, 5)");
    conn.commit();

    ResultSet rs = conn.createStatement().executeQuery(
        "SELECT FIRST_VALUES(val, 2)  WITHIN GROUP (ORDER BY dates ASC) FROM "
            + tableName + " GROUP BY page_id");

    assertTrue(rs.next());
    Assert.assertArrayEquals(new int[]{7, 9}, (int[]) rs.getArray(1).getArray());
    assertTrue(rs.next());
    Assert.assertArrayEquals(new int[]{5}, (int[]) rs.getArray(1).getArray());
    assertFalse(rs.next());
}
 
源代码21 项目: phoenix   文件: ExplainPlanWithStatsDisabledIT.java
@Test
public void testBytesRowsForHashJoin() throws Exception {
    String tableA = generateUniqueName();
    String tableB = generateUniqueName();
    String sql =
            "SELECT ta.c1.a, ta.c2.b FROM " + tableA + " ta JOIN " + tableB
                    + " tb ON ta.k = tb.k";
    try (Connection conn = DriverManager.getConnection(getUrl())) {
        initData(conn, tableA);
        initData(conn, tableB);
        assertEstimatesAreNull(sql, Lists.newArrayList(), conn);
    }
}
 
源代码22 项目: calcite-avatica   文件: ConnectionPropertiesTest.java
@Test
public void testConnectionPropertiesSync() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try {
    AvaticaConnection conn = (AvaticaConnection) DriverManager.getConnection(url);
    conn.setAutoCommit(false);
    conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

    // sync connection properties
    conn.createStatement();
    Connection remoteConn = getConnection(
            AvaticaServersForTest.PropertyRemoteJdbcMetaFactory.getInstance(PROPERTIES), conn.id);

    assertFalse(remoteConn.getAutoCommit());
    assertEquals(remoteConn.getTransactionIsolation(),
            Connection.TRANSACTION_REPEATABLE_READ);

    // after 1s, remote connection expired and reopen
    Thread.sleep(1000);

    conn.createStatement();
    Connection remoteConn1 = getConnection(
            AvaticaServersForTest.PropertyRemoteJdbcMetaFactory.getInstance(PROPERTIES), conn.id);

    assertFalse(remoteConn1.getAutoCommit());
    assertEquals(remoteConn1.getTransactionIsolation(),
            Connection.TRANSACTION_REPEATABLE_READ);
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
 
源代码23 项目: phoenix   文件: DecodeFunctionIT.java
@Test
public void invalidCharacters() throws Exception {
	Connection conn = DriverManager.getConnection(getUrl());
	String ddl = "CREATE TABLE test_table ( some_column BINARY(12) NOT NULL CONSTRAINT PK PRIMARY KEY (some_column))";

	conn.createStatement().execute(ddl);

	try {
		conn.createStatement().executeQuery("SELECT * FROM test_table WHERE some_column = DECODE('zzxxuuyyzzxxuuyy', 'hex')");
        fail();
	} catch (SQLException e) {
		assertEquals(SQLExceptionCode.ILLEGAL_DATA.getErrorCode(), e.getErrorCode());
	}
}
 
源代码24 项目: phoenix   文件: QueryMetaDataTest.java
@Test
public void testInListParameterMetaData1() throws Exception {
    String query = "SELECT a_string, b_string FROM atable WHERE a_string IN (?, ?)";
    Connection conn = DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES));
    PreparedStatement statement = conn.prepareStatement(query);
    ParameterMetaData pmd = statement.getParameterMetaData();
    assertEquals(2, pmd.getParameterCount());
    assertEquals(String.class.getName(), pmd.getParameterClassName(1));
    assertEquals(String.class.getName(), pmd.getParameterClassName(2));
}
 
源代码25 项目: phoenix   文件: UpsertWithSCNIT.java
@Test
public void testUpsertOnSCNSetMutTableWithoutIdx() throws Exception {

    helpTestUpsertWithSCNIT(false, false, true, false, false);
    prep.executeUpdate();
    props = new Properties();
    Connection conn = DriverManager.getConnection(getUrl(),props);
    ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM "+tableName);
    assertTrue(rs.next());
    assertEquals("abc", rs.getString(1));
    assertEquals("This is the first comment!", rs.getString(2));
    assertFalse(rs.next());
}
 
源代码26 项目: phoenix   文件: ProductMetricsIT.java
/**
 * Test grouped aggregation query with a mix of aggregated data types
 * @throws Exception
 */
@Test
public void testSumGroupedAggregation() throws Exception {
    long ts = nextTimestamp();
    String tenantId = getOrganizationId();
    String query = "SELECT feature,sum(unique_users),sum(cpu_utilization),sum(transactions),sum(db_utilization),sum(response_time),count(1) c FROM PRODUCT_METRICS WHERE organization_id=? AND feature < ? GROUP BY feature";
    String url = getUrl() + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(url, props);
    try {
        initTableValues(tenantId, getSplits(tenantId), ts);
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        statement.setString(2, F3);
        ResultSet rs = statement.executeQuery();
        assertTrue(rs.next());
        assertEquals(F1, rs.getString("feature"));
        assertEquals(120, rs.getInt("sum(unique_users)"));
        assertEquals(BigDecimal.valueOf(8), rs.getBigDecimal(3));
        assertEquals(1200L, rs.getLong(4));
        assertEquals(BigDecimal.valueOf(2.6), rs.getBigDecimal(5));
        assertEquals(0, rs.getLong(6));
        assertEquals(true, rs.wasNull());
        assertEquals(4, rs.getLong("c"));
        assertTrue(rs.next());
        assertEquals(F2, rs.getString("feature"));
        assertEquals(40, rs.getInt(2));
        assertEquals(BigDecimal.valueOf(3), rs.getBigDecimal(3));
        assertEquals(400L, rs.getLong(4));
        assertEquals(BigDecimal.valueOf(0.8), rs.getBigDecimal(5));
        assertEquals(0, rs.getLong(6));
        assertEquals(true, rs.wasNull());
        assertEquals(1, rs.getLong("c"));
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
源代码27 项目: dctb-utfpr-2018-1   文件: ConnectionPokemon.java
public Connection getConnection(){
    try {
        return
        DriverManager.getConnection("jdbc:mysql://localhost:3306/atividade_06?", "root","12345");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
源代码28 项目: phoenix   文件: RoundFloorCeilFuncIT.java
@Test
public void testRoundingUpDoubleInWhere() throws Exception {
	Connection conn = DriverManager.getConnection(getUrl());
	ResultSet rs = conn.createStatement().executeQuery(
       "SELECT * FROM " + tableName + " WHERE ROUND(\"DEC\", 2) = 1.26");
	assertTrue(rs.next());
}
 
源代码29 项目: ZhiHuDownLoad   文件: DaoTools.java
public static void deleteUserCache(String seed)
{
	PreparedStatement preparedStatement=null;
	Connection connection=null;
	Statement smStatement=null;
	ResultSet rsResultSet = null;
	try {
		Class.forName(driverString);
		connection=DriverManager.getConnection(conString,"sa","123456");
		preparedStatement=connection.prepareStatement("delete UserCache where id='"+seed+"'");
		preparedStatement.executeUpdate();
	} catch (Exception e) {
		e.printStackTrace();
	}
	finally
	{
		try {
			if(rsResultSet==null)
			{
				rsResultSet.close();
			}
			if(smStatement==null)
			{
				smStatement.close();
			}
			if(connection==null)
			{
				connection.close();
			}
			
		} catch (Exception e2) {

		}
	}
}
 
源代码30 项目: spacewalk   文件: RhnServletListener.java
/** {@inheritDoc} */
public void contextDestroyed(ServletContextEvent sce) {
    stopMessaging();
    logStop("Messaging");

    stopHibernate();
    logStop("Hibernate");

    if (sce == null) {
        // this has been called from the testsuite, next steps would
        // break subsequent tests
        return;
    }

    // This manually deregisters JDBC driver,
    // which prevents Tomcat from complaining about memory leaks
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            log.info("deregistering jdbc driver: " + driver);
        }
        catch (SQLException e) {
            log.warn("Error deregistering driver " + driver);
        }
    }


    // shutdown the logger to avoid ThreadDeath exception during
    // webapp reload.
    LogManager.shutdown();
}