Monday, January 6, 2014

Connecting to MSSQL Server from Java

I found this basic code snippet useful during the troubleshooting of a certain application-database connectivity issue.  It selects the date-time from the `master` DB, similar to Oracle's `dual` table used for testing purposes.  A DB user needs to exist, though you can probably use the default sysadmin `sa` user.  The project with this snippet needs to have the MSSQL JDBC driver (sqljdbc4.jar) on its project classpath.  As of now, version 4.0 of the driver can be run in JRE 7, but not JDK 7; it works fine in JDK 6.  Driver download link: Microsoft JDBC Driver 4.0 for SQL Server.

public class TestDBConnectivity { public static void main(String[] args) { String connectionUrl="jdbc:sqlserver://remoteServer:8081;DatabaseName=master;user=userName;Password=userPassword"; Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = DriverManager.getConnection(connectionUrl); String SQL = "SELECT GETDATE() AS CurrentDateTime"; stmt = con.createStatement(); rs = stmt.executeQuery(SQL); while (rs.next()) { System.out.println("result: " + rs.getString("CurrentDateTime")); } } catch (Exception e) { e.printStackTrace(); } finally { if (rs != null) try { rs.close(); } catch(Exception e) {} if (stmt != null) { try { stmt.close(); } catch(Exception e) {} } if (con != null) { try { con.close(); } catch(Exception e) {} } } } }

Source: Connecting to SQL Server 2008 from Java

No comments:

Post a Comment