How To Access MySQL Database From Java Applications?
Java is popular programming language generally used commercial and enterprise applications. MySql is popular database too which is used big service providers like Google, Facebook etc. Most of the applications generally uses data and needs to store this data in a relational database. MySQL is generally the first choice if we do not want to give money for license. In this tutorial we will look how to connect a Java applications into MySQL database in detail.
Create Context and DataSource
Jdbc MySql driver can be used to connect MySql database like below. Jdbc driver is by default provided by Java Development Kit or simply JDK.
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
- new InitialContext() creates a context for us.
Configure MySql Database Connection
MysqlDataSource dataSource = new MysqlDataSource();
- We create MySql datasource
- Then set MySql Server username and password to connect with setUser and setPassword .
- We set MySql Server address or dns name with mysql.poftut.com
Connect and Query MySql Database
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM USERS");
- We create real connection object and assign to conn
- We create query statement into stmt
- rs result set is populated with query executed by stmt
- rs, stmt, conn are closed with close function to release resources