Solution:NIIT/GNIIT Sonugiri0032@gmail.com

Sunday, November 15, 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].


  • 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);
        }
    }   
}
Share:

0 comments:

GNIITSOLUTION GNIIT SOLUTION. Powered by Blogger.

Translate

Blog Archive

Unordered List