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.
1 2 | 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
1 2 3 4 | MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUser("ahmet"); dataSource.setPassword("ali"); dataSource.setServerName("mysql.poftut.com"); |
- 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
1 2 3 4 5 6 7 | Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM USERS"); ... rs.close(); stmt.close(); conn.close(); |
- 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