Advertisement
Guest User

Untitled

a guest
Oct 13th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. package com.sqldbsamples;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.Statement;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.DriverManager;
  8.  
  9. public class App {
  10.  
  11. public static void main(String[] args) {
  12.  
  13. // Connect to database
  14. String hostName = "vo6901-sql-server.database.windows.net";
  15. String dbName = "cs-dsa-4513-sql-db";
  16. String user = "vo6901";
  17.  
  18. String url = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;", hostName, dbName, user, password);
  19. Connection connection = null;
  20.  
  21. try {
  22. connection = DriverManager.getConnection(url);
  23. String schema = connection.getSchema();
  24. System.out.println("Successful connection - Schema: " + schema);
  25.  
  26. System.out.println("Query data example:");
  27. System.out.println("=========================================");
  28.  
  29. // Create and execute a SELECT SQL statement.
  30. String selectSql = "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName "
  31. + "FROM [SalesLT].[ProductCategory] pc "
  32. + "JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid";
  33.  
  34. try (Statement statement = connection.createStatement();
  35. ResultSet resultSet = statement.executeQuery(selectSql)) {
  36.  
  37. // Print results from select statement
  38. System.out.println("Top 20 categories:");
  39. while (resultSet.next())
  40. {
  41. System.out.println(resultSet.getString(1) + " "
  42. + resultSet.getString(2));
  43. }
  44. connection.close();
  45. }
  46. }
  47. catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement