Saturday Aug 31

MySQL with Java and Maven (Tutorial)

PDF Print E-mail
Wednesday, 03 August 2011 08:16
AddThis Social Bookmark Button

MySQL with Java and Maven (Tutorial)

The following tutorial give you an example on how to connect to a MySQL database using Java and Maven to configure the JDBC driver

Configure Maven dependencies

Create the following pom to get the MySql jdbc driver library.

Maven plugin configuration




Connect and execute a sample query

The following java sample is a JUnit test. The code is doing the following :

  1. Loads the JDBC driver using the dbClass parameter
  2. Opens a connection using the login and password provided
  3. Creates and SQL statement
  4. Executes a query
  5. Iterates the resultset and display the content of the first column

Spring java source

package com.ubiteck.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import junit.framework.TestCase;

public class MySQLConnectionTest extends TestCase {

    public void testConnect() {
    String dbUrl = "jdbc:mysql://localhost/mydatabase";
    String dbClass = "com.mysql.jdbc.Driver";
    String query = "Select distinct(table_name) from INFORMATION_SCHEMA.TABLES";
    String username = "root";
    String password = "";
    try {

        Connection connection = DriverManager.getConnection(dbUrl,
            username, password);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(query);
        while ( {
        String tableName = resultSet.getString(1);
        System.out.println("Table name : " + tableName);
    } catch (ClassNotFoundException e) {
    } catch (SQLException e) {

Tags: java , maven , groupid , /groupid , artifactid , http , /artifactid , version , mysql , jdbc , driver


-4 #1 Nihal Desai 2012-11-26 05:15
:lol: i like java lanuage so that i always search java programing

Add comment

Security code

Java Tutorial on Facebook