Saturday Aug 31

Key Concepts

MySQL with Java and Maven (Tutorial)

PDFPrintE-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

<project 
    xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ubiteck</groupId>
    <artifactId>mysql-tutorial</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.17</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>

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 {

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

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

Comments  

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

Add comment


Security code
Refresh

Java Tutorial on Facebook