Java connectivity with MySQL?

Can anyone explain me how to connect Java with MySQL?

DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:

 

Context context = new InitialContext();

DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");

or instantiating and configuring one from your database driver directly:

 

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 ID FROM USERS");

...

rs.close();

stmt.close();

conn.close();

Here’s the very minimum you need to get data out of a MySQL database:

Class.forName("com.mysql.jdbc.Driver").newInstance();

Connection conn = DriverManager.getConnection

   ("jdbc:mysql://localhost:3306/foo", "root", "password");

 

Statement stmt = conn.createStatement();

stmt.execute("SELECT * FROM `FOO.BAR`");

stmt.close();

conn.close();

Add exception handling, configuration etc.to the user flexibulity