12 September 2013

Sql Server 2005 and 2008/R2 Connection string in Java

Hi Friend,

Let see how to connect to SQL Server 2005 and 2008/R2 in Java.  To establish a connection you need a jar file and an authentication dll file.

You can download both file as zip format from here.


package mssql_connection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class MsSql_Connection { public static void main(String[] args) { String url = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=testing;integratedSecurity=true;user=user_testing;password=user_password;"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection(url); Statement smt = con.createStatement(); ResultSet result = smt.executeQuery("select * from Table_1"); while(result.next()) { System.out.println(result.getInt(1)); System.out.println(result.getString(2)); } System.out.println("done"); } catch(Exception e) { e.printStackTrace(); } } }

Note --

You require two files -
   1. sqljdbcX.jar (X - version)
   2. sqljdbc_auth.dll

You can download from here.

See the image. These highlighted file and folder are required to create connection with Sql Server.

Required_jar is the folder contains a jar file. We need to add the reference of this jar file only to the project.

You can download a sample netbeans project from below given link.


Download NetBeans sample project from here.

Happy Knowledge sharing.. :)


No comments:

Post a Comment