connecting to sql server using java

Below is the code to connect to sql server using java

Prerqquisites: You need to download the sqljdbc4-2.0.jar file in to your lib folder


CODE:

package com.MyReports;

import java.sql.*;

public class sqlserver_con {


    //SQL SERVER CONNECTION
       Connection sqlcon = null;



public sqlserver_con () {

try{

// Create a variable for the connection string.

String connectionUrl = "jdbc:sqlserver://192.100.101.68:1433;databaseName=DBNAME;user=UNAME;password=PWD";


// Establish the connection

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

sqlcon = DriverManager.getConnection(connectionUrl);

}catch(Exception e) {
            System.out.println("ERROR:"+ e);
}


}


public void getData() {    
          
 ResultSet rs=null;
       
try{

// BELOW IS THE SQL QUERY IMPLEMENTATION TO SQL SERVER USING JAVA

String SQL = "SELECT TOP 10 * FROM employee.name";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);

//(OR)

//BELOW    IS THE STORED PROCEDURE IMPLEMENTATION TO SQL SERVER USING JAVA
CallableStatement stmt=sqlcon.prepareCall("{ call Get_report }");

//stmt.setString(1, val.trim());
            
stmt.execute();
             
rs = stmt.getResultSet();

while(rs.next())

{

System.out.println("VALUE:"+rs.getString("COLUMNNAME"));


}//while

stmt.close();

}
catch(Exception e1) {
//            
                
}
           
             
}    


public static void main(String[] args) {

        sqlserver_con ee = new sqlserver_con ();

        ee.getData();

        ee.closeConnection();


    }



public void closeConnection() {

try{
            
    sqlcon.close();
            
    System.out.println("closing SQLSERVER DB connection");
            
            
            
}catch(Exception e) {
    System.out.println("ERROR: "+e);
}
        

}

No comments:

Post a Comment