Macca Blog

My life experiences with code and design

JSF JDBC connection to SQL server 2005

Posted on by Mark

I have fianlly got around to figuring out how to connect to a sql server 2005 using a JDBC in JSF. Here is how my code look:

import java.sql.*;try
{
java.lang.Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
Connection connection = DriverManager.getConnection(“jdbc:sqlserver://localhost;databaseName=dbName1;user=user;password=password”);
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}

the line:

java.lang.Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);

will register the JDBC driver that I downloaded from Microsoft from the site:

http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/jdbc.mspx

so that your DriverManager class can use it for the connection.

The rest of the code is pretty self explanitory. There is plenty of doco that comes with the driver itself.

But How do I use it?

good question, I am using a class called DatabaseDelegate which will be used to connect to the database. Then once I have an instance of the DatabaseDelegate (and hence a connection to the DB) I can use the following code for execution:

DatabaseDelegate dd = new DatabaseDelegate();
Connection conn;

try
{
conn = dd.getConnection();
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(“select id, name from users”);

while (rs.next())
{
//do stuff as needed with the results
}
}
catch(Exception ex)
{
setErrorString(ex.getMessage());
}

Hope this is clear enough for any newbies to JDBC’s

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Comment

Your email address will not be published. Required fields are marked *


*