Home > Geek, Informative, Technology > A simple JDBC connection tester Cont’d

A simple JDBC connection tester Cont’d

In my earlier article I tested the JDBC using the DataSource Interface but in this article I’m going to test it using DataSource Interface with MysqlConnectionPoolDataSource.

A small requirement urged me to write the below code, I got to thank the requester.

For running the below code I used MySQL – Version 5.0.16 as the Database and Eclipse SDK – Version: 3.2.2.

Also do replace the following: DB_USER_NAME, DB_PASSWORD, DB_NAME, DB_TABLE_NAME, DB_TABLE_COLUMN_NAME

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

import javax.sql.PooledConnection;

import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;

class JdbcConTestUsinDataSrc {
public static void main(String[] args) {

MysqlConnectionPoolDataSource myDataSource = null;

if (myDataSource == null) { // first time only
myDataSource = new MysqlConnectionPoolDataSource();
myDataSource.setDatabaseName(“DB_NAME”);
myDataSource.setPassword(“DB_PASSWORD”);
myDataSource.setPort(3306);
myDataSource.setServerName(“localhost”);
myDataSource.setUser(“DB_USER_NAME”);
}

PooledConnection pc = null;
try {
pc = myDataSource.getPooledConnection();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (int i = 0; i < 5; i++) {
try {
Connection connection = pc.getConnection();

java.sql.Statement stmt;

stmt = connection.createStatement();
stmt.executeQuery(“select * from DB_TABLE_NAME”);
ResultSet resultSet = stmt.getResultSet();
while (resultSet.next()) {
System.out.println(resultSet.getString(“DB_TABLE_COLUMN_NAME”));
}

connection.close();
} catch (SQLException e) {
System.out.println(“SQLException: ” + e.getMessage());
System.out.println(“SQLState: ” + e.getSQLState());
System.out.println(“VendorError: ” + e.getErrorCode());
}
}
}
}

Categories: Geek, Informative, Technology
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.