Java Code Examples for java.sql.DriverManager

The following examples show how to use java.sql.DriverManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: tp_java_2015_02   Source File: SimpleExample.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 2
Source Project: phoenix   Source File: DistinctCountIT.java    License: Apache License 2.0 6 votes vote down vote up
@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();
        }
    }
}
 
Example 3
Source Project: Tomcat8-Source-Read   Source File: TestSlowQueryReport.java    License: MIT License 6 votes vote down vote up
@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)");
}
 
Example 4
/**
 * 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;
}
 
Example 5
Source Project: phoenix   Source File: ArithmeticQueryIT.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 6
Source Project: metadata   Source File: ScriptRunnerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
    }
 
Example 7
Source Project: Mycat2   Source File: MigrateUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
    }

}
 
Example 8
Source Project: phoenix   Source File: QueryTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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();
    }
}
 
Example 9
Source Project: ShoppingCartinJava   Source File: KidsDB.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 10
Source Project: Komondor   Source File: ConnectionTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
        }
    });
}
 
Example 11
Source Project: incubator-iotdb   Source File: IoTDBMultiSeriesIT.java    License: Apache License 2.0 6 votes vote down vote up
@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();
  }
}
 
Example 12
Source Project: flink   Source File: JdbcTableSourceITCase.java    License: Apache License 2.0 6 votes vote down vote up
@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)");
	}
}
 
Example 13
@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();
    }
}
 
Example 14
Source Project: kareldb   Source File: RemoteClusterHttpAuthTestHarness.java    License: Apache License 2.0 6 votes vote down vote up
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));
    }
}
 
Example 15
Source Project: lucene-solr   Source File: JdbcTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"));
      }
    }
  }
}
 
Example 16
Source Project: gemfirexd-oss   Source File: GFEDBManager.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 17
Source Project: phoenix   Source File: NotQueryIT.java    License: Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 18
Source Project: mysql_perf_analyzer   Source File: ConnectionFactory.java    License: Apache License 2.0 6 votes vote down vote up
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);
 }
 
Example 19
Source Project: phoenix   Source File: GlobalIndexOptimizationIT.java    License: Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 20
Source Project: phoenix   Source File: FirstValuesFunctionIT.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 21
Source Project: phoenix   Source File: ExplainPlanWithStatsDisabledIT.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 22
Source Project: calcite-avatica   Source File: ConnectionPropertiesTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
  }
}
 
Example 23
Source Project: phoenix   Source File: DecodeFunctionIT.java    License: Apache License 2.0 5 votes vote down vote up
@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());
	}
}
 
Example 24
Source Project: phoenix   Source File: QueryMetaDataTest.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 25
Source Project: phoenix   Source File: UpsertWithSCNIT.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 26
Source Project: phoenix   Source File: ProductMetricsIT.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 27
Source Project: dctb-utfpr-2018-1   Source File: ConnectionPokemon.java    License: Apache License 2.0 5 votes vote down vote up
public Connection getConnection(){
    try {
        return
        DriverManager.getConnection("jdbc:mysql://localhost:3306/atividade_06?", "root","12345");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 28
Source Project: phoenix   Source File: RoundFloorCeilFuncIT.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 29
Source Project: ZhiHuDownLoad   Source File: DaoTools.java    License: MIT License 5 votes vote down vote up
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) {

		}
	}
}
 
Example 30
Source Project: spacewalk   Source File: RhnServletListener.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@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();
}