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.
- How To Access MySQL Database From Java Applications?
Configure MySql Database Connection
We will create a new data source named
dataSource . This data source will be used to specify the database server , user name, password and other related database and connection settings.
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
We will use created and established connection names
conn . We will create a statement which will run over connection
conn and return result set named
rs . But keep in mind that after using these objects for security, performance and resource usage we need to close them properly which is generally implemented in
close() function like below.
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