tags:

views:

158

answers:

3

I am having difficulty connecting my java code to sql server database. I can connect from App server just fine..but now I want to try to connect with app server out of the picture and using InitialContext with some env properties. So a stand alone java class connecting to sql server using InitialContext

I have mssqlserver.jar in my projects libraries. Do I need some other jar as well?

I looked around for some code sample but dont know what to put in Context.INITIAL_CONTEXT_FACTORY

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "what do i put here?");
env.put("java.naming.factory.initial",
"what do i put here?");
...
what other properties would I need?

on the App server I have following properties.

datasourceName = mydb
user = myuser
port = 1433
password = mypwd
databaseName = mydb
servername = localhost
+1  A: 

You are not on the right track here. InitialContext is strictly about the application server. In order to connect to the database directly without the application server you have to create your own JDBC connection to the database, or use a different JDBC connection pool implementation.

Yishai
i knew this was gonna come up. I should have provided that in the question :). i'm writing some code that will run queries outside of the app server. so I want to connect using initialcontext...if it is not at all possible...then I will stick to JDBC?
Drake
@Drake, you have to stick with JDBC. Theoretically you could connect remotely to the application server, of course, but application servers don't generally serve datasources remotely (for good reasons). You could also reinvent the wheel and have your own JNDI implementation, but that would just do JDBC under the covers, so why bother?
Yishai
If I connect with JDBC what will be put in Class.forName("") ..considering I 'm using mssqlserver.jar
Drake
@Drake, for mssql, for Microsoft's driver it is com.microsoft.sqlserver.jdbc.SQLServerDriver. You will also have to worry about the jdbc URL, but that has to be in your application server configuration, for Sun I think it is in the server.xml.
Yishai
A: 

First of all, why don't you just use DriverManager#getConnection() for this? Imlementing and using JNDI in a (simple) client application is too much effort for a relatively little favour.

An average application server ships with its own JNDI implementation so that you don't need to worry at all about creating/defining/configuring one yourself.

If you really want to use JNDI in a client application, then start here. Much good luck with that.

BalusC
A: 

You may find it helpful to consult the JDBC tutorial, you'll see that you can use a DriverManager to get your connection. The JNDI approach you are familiar with is a nice, general abstraction for giving access to all manner of services provided in an AppServer environment. For stand-alone apps one usually just uses the raw APIs.

djna
ok...JNDI it is then.
Drake