Friday, 20 November 2015

JDBC MSSQL connection

JDBC MSSQL connection

In this article i will show you how to connect Microsoft SQL server 2012 to your java
program[JDBC].

         convenient place 
  • Download sqljdbc_auth.dll file and paste it to System32
  • Start your MSSQL server instance and login using Windows authentication

  • Go to Netbeans and create a project
  • Right click on project and go to properties










  • Go to libraries and add sqljdbc4.jar file to your project from the folder where you
  •  have extracted the downloaded driver and then click OK











  • Copy the code and paste it in Netbeans and then run the project

package javaapplication70;
import java.sql.*;
public class JavaApplication70 {

    public static void main(String[] args) {
         try {
            // Load the SQLServerDriver class, build the 
            // connection string, and get a connection 
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName
=AdventureWorks2012;integratedSecurity=true";
            // + "password=Password";
            Connection con = DriverManager.getConnection(connectionUrl);
            System.out.println("Connected.");

            // Create and execute an SQL statement that returns some data.  
            String SQL = "select DepartmentID,Name from humanresources.Department";
            java.sql.Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(SQL);

            // Iterate through the data in the result set and display it.  
            while (rs.next()) {
                System.out.println(rs.getString(1) + " " + rs.getString(2));
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.exit(0);
        }
    }   
}

No comments:

Post a Comment