How do I connect to a SQL Server 2008 database using JDBC? How do I connect to a SQL Server 2008 database using JDBC? sql-server sql-server

How do I connect to a SQL Server 2008 database using JDBC?


There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:

String userName = "username";String password = "password";String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");Connection conn = DriverManager.getConnection(url, userName, password);

after adding sqljdbc4.jar to the build path.

For Window authentication you can do something like:

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");Connection conn = DriverManager.getConnection(url);

and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).

Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!


You can use this :

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class ConnectMSSQLServer{   public void dbConnect(String db_connect_string,            String db_userid,            String db_password)   {      try {         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");         Connection conn = DriverManager.getConnection(db_connect_string,                  db_userid, db_password);         System.out.println("connected");         Statement statement = conn.createStatement();         String queryString = "select * from sysobjects where type='u'";         ResultSet rs = statement.executeQuery(queryString);         while (rs.next()) {            System.out.println(rs.getString(1));         }      } catch (Exception e) {         e.printStackTrace();      }   }   public static void main(String[] args)   {      ConnectMSSQLServer connServer = new ConnectMSSQLServer();      connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",               "<password>");   }}


I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.

Class.forName( "net.sourceforge.jtds.jdbc.Driver" );Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip     address>:1433/zacmpf", userName, password );Statement stmt = con.createStatement();