Java – How to configure a DataSource in Java to connect to MS SQL Server

datasourcejavasql-server

I'm trying to follow Java's JDBC tutorials to write a Java program that can connect to SQL Server 2008. I'm getting lost at the point of making a connection.

The following snippet is from the tutorial:

InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");
Connection con = ds.getConnection(); 

There's no explanation of what comp/env/jdbc/myDB should point to, and I don't know how I should choose a port. Also, the object ds seems to be defined twice.

I'm using the JSQLDataSource driver, for the record. Can anyone point me in the right direction here?

http://java.sun.com/docs/books/tutorial/jdbc/basics/connecting.html

Best Solution

I'm not sure anyone above has really answered the question.

I found this microsoft sample useful.

The key information in there is really that the class you need is SQLServerDataSource that is basically a configuration object - you use it something like this:

    SQLServerDataSource dataSource = new SQLServerDataSource();
    dataSource.setUser("aUser");
    dataSource.setPassword("password");
    dataSource.setServerName("hostname");
    dataSource.setDatabaseName("db");

You would then call

dataSource.getConnection();

to get a connection object which is basically the thing you use to talk to the database.

Use

connection.prepareStatement("some sql with ? substitutions");

to make something for firing off sql and:

connection.prepareCall

for calling stored procedures.