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.

  • new InitialContext() creates a context for us.

Configure MySql Database Connection

  • 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

Connect and Query MySql Database

  • 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
LEARN MORE  How To Use Mysql / MariaDB From Console?

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)