I was writing a JUnit test trying to test the connection to a SqlServer Database (i know, i know... i shouldn't unit testing for databases). The question is, I've already setup the datasource in glassfish, in fact, ping test "succeeded". But!, when i try this:
Note: The configuration is: Unit testing from Local Glassfish (where ping OK), Remote DataBase
@Test
public void simpleConnect() {
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("MyDataSource");
Connection con = dataSource.getConnection();
assertTrue(con != null && dataSource != null);
}
catch (NamingException ex) {
fail("Cannot get connection: " + ex);
}
catch (SQLException ex) {
fail("Cannot get connection: " + ex);
}
}
Nothing happens, the test never ends, NO throws Ok or Fail. I don't know exactly if I really gets the connection.
Well the idea was initially try to test the connection to the datasource and well, i was trying JUnit, but doesn't work in my case, so, i found a solution using a JSP page.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.sql.DataSource"%>
<%@page import="javax.naming.InitialContext"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test DataSource Connection</title>
</head>
<body>
<h1>Connecting to Pooled Database</h1>
<%
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("MyDataSource");
Connection connection = ds.getConnection();
if (connection == null) {
throw new SQLException("Error establishing connection!");
}
PreparedStatement stmt = null;
ResultSet result = null;
stmt = connection.prepareStatement("{call StoredProcedure(?,?)}");
stmt.setString(1, "1");
stmt.setString(2, "2");
result = stmt.executeQuery();
while (result.next()) {
out.print(result.getString(1) + "<br>");
}
%>
<h2>DataSource Working!</h2>
</body>
</html>
When you run the JSP this will retrieve the resultset of the call to the stored procedure. Obviously you can replace the call with a simple query (select * from table)
If maybe you need info about how to create, connect, and configure a datasource, look this link:http://netbeans.dzone.com/connection-pooling-glassfish-nb