Tuesday, February 24, 2015

Connecting SQL database with DriverManager

Preparation

Download sqljdbc_4.1. Then unpack it. Put 'sqljdbc41.jar' in the project as external jar. To use Trusted connection, put sqljdbc_auth.dll from \sqljdbc_4.1\enu\auth\x64 to C:\Windows\System32

3 points to remember
  1. Create connection
      Connection   con = DriverManager.getConnection(connectionUrl);

  2. Excute query
      stmt = con.createStatement();
      rs = stmt.executeQuery(SQL);

  3. Get the output
       while (rs.next()) 
   {
    System.out.println(rs.getString(1) + " " + rs.getString(2));
   }


Code

import java.sql.*;


public class DataPlay {

    public static void main(String[] args)
    {

        String connectionUrl = "jdbc:sqlserver://TJZR9XNH9H-1\\MSSQLSERVER2012:1433;" +
                "databaseName=KB;integratedSecurity=true;";//user=GreenItUser;password=GreenItUser123";
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // Establish the connection.           // Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");            con = DriverManager.getConnection(connectionUrl);

            // Create and execute an SQL statement that returns some data.            String SQL = "SELECT TOP 10 * FROM dbo.menuitem";
            stmt = con.createStatement();
            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));
            }
        }

        // Handle any errors that may have occurred.        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (rs != null) try { rs.close(); } catch(Exception e) {}
            if (stmt != null) try { stmt.close(); } catch(Exception e) {}
            if (con != null) try { con.close(); } catch(Exception e) {}
        }
    }
}

No comments:

Post a Comment