2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to connect MySQL database in java

How to connect MySQL database in java ?
userimage

The best way is to get the DataSource. There are two ways to do that


Context context = new InitialContext();

DataSource dataSource = (DataSource) context.lookup("java:com/folOne/folTwo/DB");


the other way :


MysqlDataSource dataSource = new MysqlDataSource();

dataSource.setUser("scott");

dataSource.setPassword("tiger");

dataSource.setServerName("myDBHost.example.org");


and then obtain connections from it, same as above:


Connection conn = dataSource.getConnection();

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT EMP_ID FROM EMP");

...

rs.close();

stmt.close();

conn.close();

Answer is