Java Code Examples for com.mysql.jdbc.Driver

The following examples show how to use com.mysql.jdbc.Driver. 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 check out the related API usage on the sidebar.
Example 1
Source Project: presto   Source File: MySqlClientModule.java    License: 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 Project: ats-framework   Source File: Test_DbConnMySQL.java    License: 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 3
Source Project: r-course   Source File: ConnectionTest.java    License: 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 4
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 5
Source Project: replicator   Source File: MySQLRunner.java    License: 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 6
Source Project: java_server   Source File: MybatisConfig.java    License: 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 7
Source Project: FoxTelem   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,
            "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 8
Source Project: presto   Source File: MySqlJdbcConfig.java    License: 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 9
Source Project: presto   Source File: MySqlJdbcConfig.java    License: 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 10
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 11
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 12
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 13
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 14
Source Project: r-course   Source File: ConnectionTest.java    License: 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 15
Source Project: r-course   Source File: BaseBugReport.java    License: 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 Project: StubbornJava   Source File: CMSMigrations.java    License: 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 17
Source Project: Komondor   Source File: ConnectionTest.java    License: 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 18
Source Project: Komondor   Source File: BaseBugReport.java    License: 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 19
Source Project: replicator   Source File: MySQLRunner.java    License: 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 20
Source Project: StubbornJava   Source File: CMSMigrations.java    License: 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 21
Source Project: FoxTelem   Source File: ConnectionTest.java    License: 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 22
/**
 * 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 Project: r-course   Source File: MetaDataRegressionTest.java    License: 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);
}
 
Example 24
/**
 * Tests whether bogus parameters break Driver.getPropertyInfo().
 * 
 * @throws Exception
 *             if an error occurs.
 */
public void testGetPropertyInfo() throws Exception {
    new Driver().getPropertyInfo("", null);
}