Advertisement
Guest User

Untitled

a guest
Oct 24th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package javaapplication1;
  7.  
  8. import com.sun.rowset.CachedRowSetImpl;
  9. import java.sql.Connection;
  10. import java.sql.DriverManager;
  11. import java.sql.PreparedStatement;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.sql.Statement;
  15. import javax.sql.rowset.CachedRowSet;
  16.  
  17. /**
  18. *
  19. * @author student
  20. */
  21. public class JavaApplication1 {
  22.  
  23. /**
  24. * @param args the command line arguments
  25. */
  26. public static void main(String[] args) throws SQLException {
  27.  
  28. // Create a variable for the connection string.
  29. String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
  30. "databaseName=NORTHWND;user=maciej;password=maciekmaciek";
  31.  
  32. // Declare the JDBC objects.
  33. Connection con = null;
  34. //Statement stmt = null;
  35. PreparedStatement stmt = null;
  36. ResultSet rs = null;
  37. CachedRowSet crs = new CachedRowSetImpl();
  38.  
  39. try {
  40. // Establish the connection.
  41. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  42. con = DriverManager.getConnection(connectionUrl);
  43.  
  44. /*
  45. // Create and execute an SQL statement that returns some data.
  46. String SQL = "SELECT * FROM [Customers]";
  47. stmt = con.createStatement();
  48. rs = stmt.executeQuery(SQL);
  49. */
  50.  
  51. String SQL = "SELECT * FROM [Customers] WHERE Country = ?";
  52. stmt = con.prepareStatement(SQL);
  53.  
  54. stmt.setString(1, "UK");
  55. rs = stmt.executeQuery();
  56.  
  57. crs.populate(rs);
  58.  
  59. con.close();
  60.  
  61. // Iterate through the data in the result set and display it.
  62. /*
  63. while (rs.next()) {
  64. System.out.println(rs.getString("ContactName"));
  65. }
  66. */
  67.  
  68.  
  69. while (crs.next()) {
  70. System.out.println(crs.getString("ContactName"));
  71. }
  72.  
  73. }
  74.  
  75. // Handle any errors that may have occurred.
  76. catch (Exception e) {
  77. e.printStackTrace();
  78. }
  79. finally {
  80. if (rs != null) try { rs.close(); } catch(Exception e) {}
  81. if (stmt != null) try { stmt.close(); } catch(Exception e) {}
  82. if (con != null) try { con.close(); } catch(Exception e) {}
  83. }
  84. }
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement