private void setProperties(MysqlDataSource ds, Properties properties) throws SQLException { Properties props = (Properties) properties.clone(); String url = (String) props.remove(DataSourceFactory.JDBC_URL); if (url != null) { ds.setUrl(url); } String databaseName = (String) props.remove(DataSourceFactory.JDBC_DATABASE_NAME); if (databaseName == null && url == null) { throw new SQLException("missing required property " + DataSourceFactory.JDBC_DATABASE_NAME); } ds.setDatabaseName(databaseName); String password = (String) props.remove(DataSourceFactory.JDBC_PASSWORD); ds.setPassword(password); String portNumber = (String) props.remove(DataSourceFactory.JDBC_PORT_NUMBER); if (portNumber != null) { ds.setPortNumber(Integer.parseInt(portNumber)); } String serverName = (String) props.remove(DataSourceFactory.JDBC_SERVER_NAME); ds.setServerName(serverName); String user = (String) props.remove(DataSourceFactory.JDBC_USER); ds.setUser(user); if (!props.isEmpty()) { BeanConfig.configure(ds, props); } }
MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setServerName("localhost"); dataSource.setDatabaseName("inventry"); dataSource.setPortNumber(3306); dataSource.setUser("root"); dataSource.setPassword(""); // blank password is a terrible idea Connection connection = dataSource.getConnection();
public class MySqlConnect { public static Connection connectToDB() { try { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setServerName("localhost"); dataSource.setDatabaseName("auto_lube"); dataSource.setPortNumber(3306); dataSource.setUser("root"); dataSource.setPassword("mehar"); Connection conn = dataSource.getConnection(); JOptionPane.showMessageDialog(null, "Connection established"); // better log this message return conn; } catch (Exception e) { JOptionPane.showMessageDialog(null, e); // better log the exception return null; } } }