Skip to Content
0
Former Member
Mar 12, 2007 at 05:02 AM

Connecting to SQL via EJB

17 Views

Hi all,

I need to access a SQL server from my EJB program. I have to connect to the SQL and retrieve data.This is my requirement. As of now, I am connecting to the SQL using the following code in my bean.

/********Code begins*******/

//To connect to SQL

try {

Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

Statement stmt = null;

Connection connection = null;

System.out.println("SQL Web Service");

try {

connection =

DriverManager.getConnection(

"jdbc:microsoft:sqlserver://<Hostname>:<port>",

"<Username>",

"<pwd>");

stmt = connection.createStatement();

} catch (SQLException e1) {

e1.printStackTrace();

}

// To retrieve the data from DB

ResultSet rs = null;

String return_string = null;

String query = "select * from <tablename>";

try {

rs = stmt.executeQuery(query);

while (rs.next()) {

return_string = rs.getString(1);

}

} catch (SQLException e2) {

e2.printStackTrace();

}

try {

connection.close();

} catch (SQLException e3) {

e3.printStackTrace();

}

return return_string;

/*****Code ends*******/

This is what I've done now. But it doesn't work!! When I deploy the EAR and run , I get the following exception.

com.sap.engine.services.ejb.exceptions.BaseRemoteException

Can someone help me with the right way of connecting to SQL server from EJB. I need to expose this as a web service later.

Thanks & Regards,

M.Subathra