com.mysql.jdbc.Driver Java Examples

The following examples show how to use com.mysql.jdbc.Driver. 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 check out the related API usage on the sidebar.
Example #1
Source File: MySqlClientModule.java    From presto with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
@ForBaseJdbc
public static ConnectionFactory createConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider, MySqlConfig mySqlConfig)
        throws SQLException
{
    Properties connectionProperties = new Properties();
    connectionProperties.setProperty("useInformationSchema", Boolean.toString(mySqlConfig.isDriverUseInformationSchema()));
    connectionProperties.setProperty("nullCatalogMeansCurrent", "false");
    connectionProperties.setProperty("useUnicode", "true");
    connectionProperties.setProperty("characterEncoding", "utf8");
    connectionProperties.setProperty("tinyInt1isBit", "false");
    if (mySqlConfig.isAutoReconnect()) {
        connectionProperties.setProperty("autoReconnect", String.valueOf(mySqlConfig.isAutoReconnect()));
        connectionProperties.setProperty("maxReconnects", String.valueOf(mySqlConfig.getMaxReconnects()));
    }
    if (mySqlConfig.getConnectionTimeout() != null) {
        connectionProperties.setProperty("connectTimeout", String.valueOf(mySqlConfig.getConnectionTimeout().toMillis()));
    }

    return new DriverConnectionFactory(
            new Driver(),
            config.getConnectionUrl(),
            connectionProperties,
            credentialProvider);
}
 
Example #2
Source File: ConnectionTest.java    From FoxTelem with 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,
            "Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: The database 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 #3
Source File: MybatisConfig.java    From java_server with MIT License 6 votes vote down vote up
private void druidSettings(DruidDataSource druidDataSource) throws Exception {
    druidDataSource.setMaxActive(1000);
    druidDataSource.setInitialSize(0);
    druidDataSource.setMinIdle(0);
    druidDataSource.setMaxWait(60000);
    druidDataSource.setPoolPreparedStatements(true);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(100);
    druidDataSource.setTestOnBorrow(false);
    druidDataSource.setTestOnReturn(false);
    druidDataSource.setTestWhileIdle(true);
    druidDataSource.setTimeBetweenEvictionRunsMillis(6000);
    druidDataSource.setMinEvictableIdleTimeMillis(2520000);
    druidDataSource.setRemoveAbandoned(true);
    druidDataSource.setRemoveAbandonedTimeout(18000);
    druidDataSource.setLogAbandoned(true);
    druidDataSource.setFilters("mergeStat");
    druidDataSource.setDriver(new Driver());
}
 
Example #4
Source File: MySQLRunner.java    From replicator with Apache License 2.0 6 votes vote down vote up
public List<HashMap<String,Object>> runMysqlQuery(ServicesControl mysql,
                           MySQLConfiguration configuration,
                           String query,
                           boolean runAsRoot) {
    Statement statement;
    BasicDataSource dataSource = initDatasource(mysql, configuration, Driver.class.getName(), runAsRoot);
    try (Connection connection = dataSource.getConnection()) {
        statement = connection.createStatement();
        LOG.debug("Executing query - " + query);

        if (!query.trim().equals("")) {
            statement.execute(query);
        }

        ResultSet result = statement.getResultSet();
        return convertResultSetToList(result);
    } catch (Exception exception) {
        LOG.warn(String.format("error executing query \"%s\": %s",
                query, exception.getMessage()));
        return null;
    }

}
 
Example #5
Source File: Test_DbConnMySQL.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void accessors() {

    Map<String, Object> customProperties = new HashMap<String, Object>();
    customProperties.put(DbKeys.PORT_KEY, 123);

    DbConnMySQL dbConnection = new DbConnMySQL("host", "db", "user", "pass", customProperties);

    assertEquals(DbConnMySQL.DATABASE_TYPE, dbConnection.getDbType());
    assertEquals("host", dbConnection.getHost());
    assertEquals("db", dbConnection.getDb());
    assertEquals("user", dbConnection.getUser());
    assertEquals("pass", dbConnection.getPassword());
    assertEquals("jdbc:mysql://host:123/db", dbConnection.getURL());
    assertTrue(dbConnection.getConnHash().startsWith("host_123_db"));
    assertEquals("MySQL connection to host:123/db", dbConnection.getDescription());
    assertEquals(Driver.class, dbConnection.getDriverClass());
}
 
Example #6
Source File: ConnectionTest.java    From r-course with MIT License 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 #7
Source File: MySqlJdbcConfig.java    From presto with Apache License 2.0 5 votes vote down vote up
@AssertTrue(message = "Invalid JDBC URL for MySQL connector")
public boolean isUrlValid()
{
    try {
        Driver driver = new Driver();
        Properties properties = driver.parseURL(getConnectionUrl(), null);
        return properties != null;
    }
    catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: ConnectionTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test for Driver.acceptsURL() behavior clarification:
 * - acceptsURL() throws SQLException if URL is null.
 */
public void testDriverAcceptsURLNullArgument() {
    assertThrows(SQLException.class, "The database URL cannot be null.", new Callable<Void>() {
        public Void call() throws Exception {
            Driver mysqlDriver = new Driver();
            mysqlDriver.acceptsURL(null);
            return null;
        }
    });
}
 
Example #9
Source File: CMSMigrations.java    From StubbornJava with MIT License 5 votes vote down vote up
public static void codegen() throws Exception {
    List<ForcedType> forcedTypes = JooqConfig.defaultForcedTypes();

    HikariDataSource ds = CMSConnectionPools.processing();

    Configuration configuration = new Configuration()
        .withJdbc(new Jdbc()
            .withDriver(Driver.class.getName())
            .withUrl(ds.getJdbcUrl())
            .withUser(ds.getUsername())
            .withPassword(ds.getPassword()))
        .withGenerator(new Generator()
            .withDatabase(new Database()
                .withName(MySQLDatabase.class.getName())
                .withIncludes(".*")
                .withExcludes("")
                .withIncludeExcludeColumns(true)
                .withForcedTypes(forcedTypes)
                .withInputSchema("sj_cms"))
            .withGenerate(new Generate()
                .withJavaTimeTypes(true))
            .withStrategy(new Strategy()
                .withName(CustomGeneratorStrategy.class.getName()))
            .withTarget(new Target()
                .withPackageName("com.stubbornjava.cms.server.generated")
                .withDirectory("src/generated/java")));

    GenerationTool.generate(configuration);
}
 
Example #10
Source File: MySQLRunner.java    From replicator with Apache License 2.0 5 votes vote down vote up
public boolean runMysqlScript(ServicesControl mysql,
                              MySQLConfiguration configuration,
                              String scriptFilePath,
                              Map<String, String> scriptParams,
                              boolean runAsRoot) {
    Statement statement;
    BasicDataSource dataSource = initDatasource(mysql, configuration, Driver.class.getName(), runAsRoot);
    try (Connection connection = dataSource.getConnection()) {
        statement = connection.createStatement();
        LOG.info("Executing query from " + scriptFilePath);
        String s;
        StringBuilder sb = new StringBuilder();
        File filehandle = new File(scriptFilePath);
        FileReader fr = new FileReader(filehandle);
        BufferedReader br = new BufferedReader(fr);
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        br.close();

        StrSubstitutor sub = new StrSubstitutor(scriptParams, "{", "}");
        String subSb = sub.replace(sb);

        String[] inst = subSb.split(";");
        for (String query : inst) {
            if (!query.trim().equals("")) {
                statement.execute(query);
                LOG.debug("Query executed - " + query);
            }
        }
        return true;
    } catch (Exception exception) {
        throw new RuntimeException(String.format("error executing query \"%s\": %s",
                scriptFilePath, exception.getMessage()));
    }

}
 
Example #11
Source File: BaseBugReport.java    From Komondor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor for this BugReport, sets up JDBC driver used to create
 * connections.
 */
public BaseBugReport() {
    try {
        this.driver = new Driver();
    } catch (SQLException ex) {
        throw new RuntimeException(ex.toString());
    }
}
 
Example #12
Source File: ConnectionTest.java    From Komondor with GNU General Public License v3.0 5 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 #13
Source File: ConnectionTest.java    From Komondor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test for Driver.acceptsURL() behavior clarification:
 * - acceptsURL() throws SQLException if URL is null.
 */
public void testDriverAcceptsURLNullArgument() {
    assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
        public Void call() throws Exception {
            Driver mysqlDriver = new Driver();
            mysqlDriver.acceptsURL(null);
            return null;
        }
    });
}
 
Example #14
Source File: CMSMigrations.java    From StubbornJava with MIT License 5 votes vote down vote up
public static void codegen() throws Exception {
    List<ForcedType> forcedTypes = JooqConfig.defaultForcedTypes();

    HikariDataSource ds = CMSConnectionPools.processing();

    Configuration configuration = new Configuration()
        .withJdbc(new Jdbc()
            .withDriver(Driver.class.getName())
            .withUrl(ds.getJdbcUrl())
            .withUser(ds.getUsername())
            .withPassword(ds.getPassword()))
        .withGenerator(new Generator()
            .withDatabase(new Database()
                .withName(MySQLDatabase.class.getName())
                .withIncludes(".*")
                .withExcludes("")
                .withIncludeExcludeColumns(true)
                .withForcedTypes(forcedTypes)
                .withInputSchema("sj_cms"))
            .withGenerate(new Generate()
                .withJavaTimeTypes(true))
            .withStrategy(new Strategy()
                .withName(CustomGeneratorStrategy.class.getName()))
            .withTarget(new Target()
                .withPackageName("com.stubbornjava.cms.server.generated")
                .withDirectory("src/generated/java")));

    GenerationTool.generate(configuration);
}
 
Example #15
Source File: BaseBugReport.java    From r-course with MIT License 5 votes vote down vote up
/**
 * Constructor for this BugReport, sets up JDBC driver used to create
 * connections.
 */
public BaseBugReport() {
    try {
        this.driver = new Driver();
    } catch (SQLException ex) {
        throw new RuntimeException(ex.toString());
    }
}
 
Example #16
Source File: ConnectionTest.java    From r-course with MIT License 5 votes vote down vote up
/**
 * Test for Driver.acceptsURL() behavior clarification:
 * - acceptsURL() throws SQLException if URL is null.
 */
public void testDriverAcceptsURLNullArgument() {
    assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
        public Void call() throws Exception {
            Driver mysqlDriver = new Driver();
            mysqlDriver.acceptsURL(null);
            return null;
        }
    });
}
 
Example #17
Source File: MysqlChannelTest.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static JdbcTemplate getJdbcTemplate() throws UnknownHostException {
  MysqlConnection connection = new MysqlConnection("192.168.1.204", 3306, System.getenv("MYSQL_USER"), System.getenv("MYSQL_PASS"));

  HikariConfig config = connection.toConfig();
  config.setDriverClassName(Driver.class.getName());
  config.setInitializationFailTimeout(-1);
  HikariDataSource hikariDataSource = new HikariDataSource(config);

  return new JdbcTemplate(hikariDataSource);
}
 
Example #18
Source File: MysqlConnection.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public DataSource dataSource() {
  String className = Driver.class.getName();
  HikariConfig config = toConfig();
  config.setDriverClassName(className);
  // A value less than zero will not bypass any connection attempt and validation during startup,
  // and therefore the pool will start immediately
  config.setInitializationFailTimeout(-1);
  return new HikariDataSource(config);
}
 
Example #19
Source File: ConsumerSchemaMeta.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static TableMeta tableMeta(MysqlConnection connection, String schema, String table) throws SQLException {
  String jdbcUrl = connection.toConnectionUrl(schema);
  DataSource dataSource = new DriverDataSource(jdbcUrl, Driver.class.getName(), new Properties(),
      connection.getUser(), connection.getPassword());
  Consumer single = Consumer.singleTable(schema, table);
  HashMap<Consumer, List<SchemaMeta>> res;
  try (Connection dataSourceConnection = dataSource.getConnection()) {
    DatabaseMetaData metaData = dataSourceConnection.getMetaData();
    try (ResultSet tableResultSet = metaData
        .getTables(schema, null, table, new String[]{"TABLE"})) {
      res = getSchemaMeta(metaData, tableResultSet, Sets.newHashSet(single));
    }
  }
  return res.get(single).get(0).findTable(schema, table);
}
 
Example #20
Source File: ConsumerSchemaMeta.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MetaDataBuilder(MysqlConnection connection,
                       HashMap<Consumer, ProducerSink> consumerSink) throws SQLException {
  this.consumerSink = consumerSink;
  Set<String> merged = consumerSink.keySet().stream().map(Consumer::getRepos)
      .flatMap(Set::stream).map(Repo::getConnectionName).collect(Collectors.toSet());
  calculatedSchemaName = getSchemaName(merged);
  jdbcUrl = connection.toConnectionUrl(calculatedSchemaName);
  dataSource = new DriverDataSource(jdbcUrl,
      Driver.class.getName(), new Properties(),
      connection.getUser(), connection.getPassword());
  dataSource.setLoginTimeout(TIMEOUT);
}
 
Example #21
Source File: MySqlJdbcConfig.java    From presto with Apache License 2.0 5 votes vote down vote up
@AssertTrue(message = "Database (catalog) must not be specified in JDBC URL for MySQL connector")
public boolean isUrlWithoutDatabase()
{
    try {
        Driver driver = new Driver();
        Properties properties = driver.parseURL(getConnectionUrl(), null);
        return (properties == null) || (driver.database(properties) == null);
    }
    catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: CommonUtils.java    From fiware-cygnus with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Only works in DEBUG level.
 * Prints the loaded .jar files at the start of Cygnus run.
 */
public static void printLoadedJars() {
    // trace the file containing the httpclient library
    URL myClassURL = PoolingClientConnectionManager.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading httpclient from " + myClassURL.toExternalForm());
    
    // trace the file containing the httpcore library
    myClassURL = DefaultBHttpServerConnection.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading httpcore from " + myClassURL.toExternalForm());
    
    // trace the file containing the junit library
    myClassURL = ErrorCollector.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading junit from " + myClassURL.toExternalForm());
    
    // trace the file containing the flume-ng-node library
    myClassURL =
            RegexExtractorInterceptorMillisSerializer.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading flume-ng-node from " + myClassURL.toExternalForm());
    
    // trace the file containing the libthrift library
    myClassURL = ListMetaData.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading libthrift from " + myClassURL.toExternalForm());
    
    // trace the file containing the gson library
    myClassURL = JsonPrimitive.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading gson from " + myClassURL.toExternalForm());
    
    // trace the file containing the json-simple library
    myClassURL = Yytoken.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading json-simple from " + myClassURL.toExternalForm());
    
    // trace the file containing the mysql-connector-java library
    myClassURL = Driver.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading mysql-connector-java from " + myClassURL.toExternalForm());
    
    // trace the file containing the postgresql library
    myClassURL = BlobOutputStream.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading postgresql from " + myClassURL.toExternalForm());
    
    // trace the file containing the log4j library
    myClassURL = SequenceNumberPatternConverter.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading log4j from " + myClassURL.toExternalForm());
    
    // trace the file containing the hadoop-core library
    myClassURL = AbstractMetricsContext.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading hadoop-core from " + myClassURL.toExternalForm());
    
    // trace the file containing the hive-exec library
    myClassURL = AbstractMapJoinOperator.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading hive-exec from " + myClassURL.toExternalForm());
    
    // trace the file containing the hive-jdbc library
    myClassURL = HivePreparedStatement.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading hive-jdbc from " + myClassURL.toExternalForm());
    
    // trace the file containing the mongodb-driver library
    myClassURL = AsyncReadWriteBinding.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading mongodb-driver from " + myClassURL.toExternalForm());
    
    // trace the file containing the kafka-clients library
    myClassURL = OffsetOutOfRangeException.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading kafka-clientsc from " + myClassURL.toExternalForm());
    
    // trace the file containing the zkclient library
    myClassURL = ZkNoNodeException.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading zkclient from " + myClassURL.toExternalForm());
    
    // trace the file containing the kafka_2.11 library
    myClassURL = KafkaMigrationTool.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading kafka_2.11 from " + myClassURL.toExternalForm());
    
    // trace the file containing the aws-java-sdk-dynamodb library
    myClassURL = WriteRequest.class.getProtectionDomain().getCodeSource().getLocation();
    LOGGER.debug("Loading aws-java-sdk-dynamodb from " + myClassURL.toExternalForm());

}
 
Example #23
Source File: MetaDataRegressionTest.java    From Komondor with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Tests whether bogus parameters break Driver.getPropertyInfo().
 * 
 * @throws Exception
 *             if an error occurs.
 */
public void testGetPropertyInfo() throws Exception {
    new Driver().getPropertyInfo("", null);
}
 
Example #24
Source File: MetaDataRegressionTest.java    From r-course with MIT License 2 votes vote down vote up
/**
 * Tests whether bogus parameters break Driver.getPropertyInfo().
 * 
 * @throws Exception
 *             if an error occurs.
 */
public void testGetPropertyInfo() throws Exception {
    new Driver().getPropertyInfo("", null);
}