Connecting to MySql from java with Maven

In this example we will be creating a simple maven java project to connect to the local mysql instance, without actually installing any jdbc connector and setting it to classpath (maven will take care of this :))

1. Add MySQL connector maven dependency in the pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<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.automatethebox</groupId>
    <artifactId>mysql-connect-maven</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
    </dependencies>
</project>

2. Sample java source file: Connecting to local mysql instance and listing tables;

package com.automatethebox.mysql_connect_maven;

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

public class MySqlConnectionWithMaven {

    public static void main(String[] args) {

        // Databases url (here 'information_schema' is database name)
        String databaseUrl = "jdbc:mysql://localhost/information_schema";
        String jdbcConnectorClass = "com.mysql.jdbc.Driver";
        String mysqlUser = "root";
        String myUserPass = "Admin@123";
        String query = "Select distinct(table_name) from INFORMATION_SCHEMA.TABLES";

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

Comments

Popular posts from this blog

Use environment variable in Jenkins editable email notification subject.

How i tricked IntelliJ IDEA ultimate edition to keep running even after the trial period.

How to locate element in Html 'svg' tag in Selenium 2(Webdriver)