By Administrator Updated: Saturday, 06 August 2011 21:47
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.
<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 :
-
Loads the JDBC driver using the dbClass parameter
-
Opens a connection using the login and password provided
-
Creates and SQL statement
-
Executes a query
-
Iterates the resultset and display the content of the first column
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
Add comment
Comments
RSS feed for comments to this post