Java Code Examples for com.mysql.jdbc.jdbc2.optional.MysqlDataSource#setUser()

The following examples show how to use com.mysql.jdbc.jdbc2.optional.MysqlDataSource#setUser() . 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: TestDbSessionPropertyManagerIntegration.java    From presto with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setupTest()
{
    queryRunner.getCoordinator().getSessionPropertyDefaults()
            .setConfigurationManager("db-test", ImmutableMap.<String, String>builder()
                    .put("session-property-manager.db.url", mysqlContainer.getJdbcUrl())
                    .put("session-property-manager.db.username", mysqlContainer.getUsername())
                    .put("session-property-manager.db.password", mysqlContainer.getPassword())
                    .build());

    MysqlDataSource dataSource = new MysqlDataSource();
    dataSource.setURL(mysqlContainer.getJdbcUrl());
    dataSource.setUser(mysqlContainer.getUsername());
    dataSource.setPassword(mysqlContainer.getPassword());
    dao = Jdbi.create(dataSource)
            .installPlugin(new SqlObjectPlugin())
            .onDemand(SessionPropertiesDao.class);
}
 
Example 2
Source File: TestDB.java    From Java-Data-Science-Cookbook with MIT License 6 votes vote down vote up
public void readTable(String user, String password, String server){
     MysqlDataSource dataSource = new MysqlDataSource();
     dataSource.setUser(user);
     dataSource.setPassword(password);
     dataSource.setServerName(server);
     try{
          Connection conn = dataSource.getConnection();
          Statement stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("SELECT * FROM data_science.books");
          while (rs.next()){
               int id = rs.getInt("id");
               String book = rs.getString("book_name");
               String author = rs.getString("author_name");
               Date dateCreated = rs.getDate("date_created");
               System.out.format("%s, %s, %s, %s\n", id, book, author, dateCreated);
          }
          rs.close();
          stmt.close();
          conn.close();
     }catch (Exception e){
          //Your exception handling mechanism goes here.
     }
}
 
Example 3
Source File: DataIntegrityTestTool.java    From adt with Apache License 2.0 6 votes vote down vote up
public DataIntegrityTestTool(Properties prop) throws Exception{
    
    this.setName("data-integrity-test-thread");
    
    srcDs = new MysqlDataSource();
    srcDs.setURL(prop.getProperty(DMLQueryTool.PROP_MSR_SRC_URL));
    srcDs.setUser(prop.getProperty(DMLQueryTool.PROP_MSR_SRC_USERNAME));
    srcDs.setPassword(prop.getProperty(DMLQueryTool.PROP_MSR_SRC_PASSWROD));
    
    destCount = Integer.parseInt(prop.getProperty(DMLQueryTool.PROP_MSR_DEST_COUNT));
    destDs = new MysqlDataSource[destCount];
    for(int i=0; i<destCount; i++){
        destDs[i] = new MysqlDataSource();
        destDs[i].setURL(prop.getProperty(String.format(DMLQueryTool.PROP_MSR_DEST_URL, i)));
        destDs[i].setUser(prop.getProperty(String.format(DMLQueryTool.PROP_MSR_DEST_USERNAME, i)));
        destDs[i].setPassword(prop.getProperty(String.format(DMLQueryTool.PROP_MSR_DEST_PASSWORD, i)));
    }
}
 
Example 4
Source File: MysqlBinlogProcessorDBCopyTest.java    From adt with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception{
    initializeTestEnv();
    
    final int sleepCount = 30;
    
    LOGGER.debug("sleep " + sleepCount + "sec for generating enough test data");
    for(int i=1; i<=sleepCount; i++){
        LOGGER.debug(i + "/" + sleepCount);
        Thread.sleep(1000);
    }
    
    // create dataSource
    dataSource = new MysqlDataSource();
    dataSource.setUrl(DB_URL);
    dataSource.setUser(DB_USER);
    dataSource.setPassword(DB_PW);
    
    
}
 
Example 5
Source File: MySqlTestSettings.java    From dashbuilder with Apache License 2.0 6 votes vote down vote up
@Override
public SQLDataSourceLocator getDataSourceLocator() {
    return new SQLDataSourceLocator() {
        public DataSource lookup(SQLDataSetDef def) throws Exception {
            String url = connectionSettings.getProperty("url");
            String user = connectionSettings.getProperty("user");
            String password = connectionSettings.getProperty("password");

            MysqlDataSource ds = new MysqlDataSource();
            ds.setURL(url);
            if (!StringUtils.isBlank(user)) {
                ds.setUser(user);
            }
            if (!StringUtils.isBlank(password)) {
                ds.setPassword(password);
            }
            return ds;
        }
    };
}
 
Example 6
Source File: BaseVersionedMySQLSupport.java    From boon with Apache License 2.0 6 votes vote down vote up
/**
 * Connects to the DB and tracks if successful so upstream stuff can try to reconnect.
 */
protected void connect() {

    try {
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setURL(url);
        dataSource.setPassword(password);
        dataSource.setUser(userName);
        connection = dataSource.getConnection();
        connection.setAutoCommit(true);
        closed = false;
        totalConnectionOpen++;
    } catch (SQLException sqlException) {
        this.closed = true;
        connection = null;

        handle("Unable to connect", sqlException);

    }


}
 
Example 7
Source File: BaseMySQLSupport.java    From boon with Apache License 2.0 6 votes vote down vote up
protected void connect() {

        try {
            MysqlDataSource dataSource = new MysqlDataSource();
            dataSource.setURL(url);
            dataSource.setPassword(password);
            dataSource.setUser(userName);
            connection = dataSource.getConnection();
            connection.setAutoCommit(true);
            closed = false;
            totalConnectionOpen++;
        } catch (SQLException sqlException) {
            this.closed = true;
            connection = null;

            handle("Unable to connect", sqlException);

        }


    }
 
Example 8
Source File: ITTracingStatementInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@Before public void init() throws SQLException {
  StringBuilder url = new StringBuilder("jdbc:mysql://");
  url.append(envOr("MYSQL_HOST", "127.0.0.1"));
  url.append(":").append(envOr("MYSQL_TCP_PORT", 3306));
  String db = envOr("MYSQL_DB", null);
  if (db != null) url.append("/").append(db);
  url.append("?statementInterceptors=").append(TracingStatementInterceptor.class.getName());
  url.append("&zipkinServiceName=").append("myservice");

  MysqlDataSource dataSource = new MysqlDataSource();
  dataSource.setUrl(url.toString());

  dataSource.setUser(System.getenv("MYSQL_USER"));
  assumeTrue("Minimally, the environment variable MYSQL_USER must be set",
    dataSource.getUser() != null);
  dataSource.setPassword(envOr("MYSQL_PASS", ""));
  connection = dataSource.getConnection();
  spans.clear();
}
 
Example 9
Source File: MysqlClient.java    From SpinalTap with Apache License 2.0 5 votes vote down vote up
public static MysqlDataSource createMysqlDataSource(
    String host,
    int port,
    String user,
    String password,
    boolean mTlsEnabled,
    TlsConfiguration tlsConfig) {
  MysqlDataSource dataSource = new MysqlConnectionPoolDataSource();

  dataSource.setUser(user);
  dataSource.setPassword(password);
  dataSource.setServerName(host);
  dataSource.setPort(port);
  dataSource.setJdbcCompliantTruncation(false);
  dataSource.setAutoReconnectForConnectionPools(true);

  if (mTlsEnabled && tlsConfig != null) {
    dataSource.setUseSSL(true);
    if (tlsConfig.getKeyStoreFilePath() != null && tlsConfig.getKeyStorePassword() != null) {
      dataSource.setClientCertificateKeyStoreUrl("file:" + tlsConfig.getKeyStoreFilePath());
      dataSource.setClientCertificateKeyStorePassword(tlsConfig.getKeyStorePassword());
    }
    if (tlsConfig.getKeyStoreType() != null) {
      dataSource.setClientCertificateKeyStoreType(tlsConfig.getKeyStoreType());
    }
    if (tlsConfig.getTrustStoreFilePath() != null && tlsConfig.getTrustStorePassword() != null) {
      dataSource.setTrustCertificateKeyStoreUrl("file:" + tlsConfig.getTrustStoreFilePath());
      dataSource.setTrustCertificateKeyStorePassword(tlsConfig.getTrustStorePassword());
    }
    if (tlsConfig.getTrustStoreType() != null) {
      dataSource.setTrustCertificateKeyStoreType(tlsConfig.getTrustStoreType());
    }
  }

  return dataSource;
}
 
Example 10
Source File: BookRecommender.java    From Machine-Learning-in-Java with MIT License 5 votes vote down vote up
public static DataModel loadFromDB() throws Exception {
	
	// Database-based DataModel - MySQLJDBCDataModel
	/*
	 * A JDBCDataModel backed by a PostgreSQL database and accessed via
	 * JDBC. It may work with other JDBC databases. By default, this class
	 * assumes that there is a DataSource available under the JNDI name
	 * "jdbc/taste", which gives access to a database with a
	 * "taste_preferences" table with the following schema: CREATE TABLE
	 * taste_preferences ( user_id BIGINT NOT NULL, item_id BIGINT NOT NULL,
	 * preference REAL NOT NULL, PRIMARY KEY (user_id, item_id) ) CREATE
	 * INDEX taste_preferences_user_id_index ON taste_preferences (user_id);
	 * CREATE INDEX taste_preferences_item_id_index ON taste_preferences
	 * (item_id);
	 */
	MysqlDataSource dbsource = new MysqlDataSource();
	dbsource.setUser("user");
	dbsource.setPassword("pass");
	dbsource.setServerName("localhost");
	dbsource.setDatabaseName("my_db");

	DataModel dataModelDB = new MySQLJDBCDataModel(dbsource,
			"taste_preferences", "user_id", "item_id", "preference",
			"timestamp");
	
	return dataModelDB;
}
 
Example 11
Source File: HandlerTest.java    From adt with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void beforeClass() throws Exception{
    initializeTestEnv();
    
    final int sleepCount = 30;
    
    LOGGER.debug("sleep " + sleepCount + "sec for generating enough test data");
    for(int i=1; i<=sleepCount; i++){
        LOGGER.debug(i + "/" + sleepCount);
        Thread.sleep(1000);
    }
    
    dataSource = new MysqlDataSource();
    dataSource.setURL(DB_URL);
    dataSource.setUser(DB_USER);
    dataSource.setPassword(DB_PW);
    
    for(int i=0; i<SHARD_COUNT; i++){
        
        Connection connDest = DriverManager.getConnection(DB_DEST_URL_LIST_WITHOUT_SCHEMA[i], DB_USER, DB_PW);
        try{
            Statement stmt = connDest.createStatement();
            stmt.execute("DROP DATABASE IF EXISTS " + DB_DEST_SCHEMA_LIST[i]);
            stmt.execute("CREATE DATABASE " + DB_DEST_SCHEMA_LIST[i]);
            stmt.execute(String.format(TestUtil.getResourceAsString("sql/create_table_adt_test_1.sql"), DB_DEST_SCHEMA_LIST[i]));
            stmt.execute(String.format(TestUtil.getResourceAsString("sql/create_table_adt_test_2.sql"), DB_DEST_SCHEMA_LIST[i]));
            stmt.execute(String.format(TestUtil.getResourceAsString("sql/create_table_adt_test_3.sql"), DB_DEST_SCHEMA_LIST[i]));
        }finally{
            connDest.close();
        }
        
    }
        
}
 
Example 12
Source File: HandlerTest.java    From adt with Apache License 2.0 5 votes vote down vote up
public static Connection getConnection(String url, String username, String password) throws SQLException{
    MysqlDataSource ds = new MysqlDataSource();
    ds.setUrl(url);
    ds.setUser(username);
    ds.setPassword(password);
    return ds.getConnection();
}
 
Example 13
Source File: Util.java    From DKO with GNU Lesser General Public License v2.1 5 votes vote down vote up
public synchronized static DataSource getDS() {
	if (ds==null) {
		MysqlDataSource tmpDS = new MysqlDataSource();
		tmpDS.setURL("jdbc:mysql://localhost/sakila");
		tmpDS.setUser("root");
		tmpDS.setPassword("");
		ds = tmpDS;
	}
	return ds;
}
 
Example 14
Source File: TestMySQLDB.java    From DKO with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void setUp() throws Exception {
	super.setUp();
	MysqlDataSource mysqlDS = new MysqlDataSource();
	mysqlDS.setUser("root");
	mysqlDS.setDatabaseName("nosco_test_jpetstore");
	ds = mysqlDS;
	Context vmContext = Context.getVMContext();
	vmContext.setDataSource(ds).setAutoUndo(false);
	//vmContext.overrideSchema(ds, "public", "nosco_test_jpetstore").setAutoUndo(false);
	ccds = new ConnectionCountingDataSource(ds);
	//vmContext.overrideSchema(ccds, "public", "nosco_test_jpetstore").setAutoUndo(false);
}
 
Example 15
Source File: SampleLoop.java    From DKO with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param args
 */
public static void main(final String[] args) {
	final MysqlDataSource ds = new MysqlDataSource();
	ds.setUser("root");
	ds.setDatabaseName("nosco_test_jpetstore");
	final Query<Item> items = Item.ALL.use(ds);
	System.err.println("about to start...");
	int count = 0;
	for (final Item item : items) {
		item.getAttr1();
		item.getAttr3();
		++count;
	}
	System.err.println("...done! "+ count);
}
 
Example 16
Source File: DbUtilsDemo.java    From JavaTutorial with Apache License 2.0 3 votes vote down vote up
/**
 * 创建JDBC连接池。
 * 
 * @param pros 数据库连接信息,里面包含4个键值对。
 * <pre>
 * jdbcDriver => JDBC驱动类名称
 * url => 数据库JDBC连接地址
 * user => 连接数据库的用户名
 * password => 连接数据库的密码
 * <pre>
 * @return 连接池对象
 */
private DataSource createDataSource(Properties pros) {
    MysqlDataSource ds = new MysqlDataSource();
    ds.setURL(pros.getProperty("url"));
    ds.setUser(pros.getProperty("user"));
    ds.setPassword(pros.getProperty("password"));
    
    return ds;
}