Thursday, April 16, 2015

SQL Server DB : Simple JDBC program

public class SqlServerJDBC {

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 userName = "sa";
                String password = "12345";
                String serverport="1433";
                String serverip = "localhost";
                String dbName = "adventureworks_DW";
                String url = "jdbc:sqlserver://"+serverip+"\\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
             
             
                Connection con = DriverManager.getConnection(url, userName, password);
                Statement s1 = con.createStatement();
           System.out.println("Connected.");

           // Create and execute an SQL statement that returns some data.
           String SQL = "SELECT firstname, lastname FROM dimcustomer";
           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)
      {
          e.printStackTrace();
      System.out.println(e.getMessage());
           System.exit(0);
      }

}

}

No comments:

Post a Comment