/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. import java.sql.*; 

2.  

3. public class JDBCQ 

4.

5.   public static void 

6.     main ( String[] args ) 

7.   { 

8.     Connection connection  = null

9.     try

10.       DriverManager.registerDriver 

11.       ( new sun.jdbc.odbc.JdbcOdbcDriver() ); 

12.        

13.       connection = DriverManager.getConnection 

14.         ( "jdbc:odbc:ourdb"

15.             "hotshot"

16.               "Geiger" ); 

17.          

18.       Statement stm = connection.createStatement (); 

19.  

20.       ResultSet rs = stm.executeQuery 

21.         ("SELECT * FROM Products" ); 

22.        

23.       while (rs.next ()) 

24.       { 

25.         String strnaam = rs.getString ("Name"); 

26.         System.out.println ( strnaam ); 

27.       } 

28.     } 

29.     catch ( SQLException ex ) { 

30.       System.out.println ("Error : " + ex ); 

31.     } 

32.     finally { 

33.       try

34.         if (connection != null

35.           connection.close (); 

36.       } 

37.       catch ( Exception e ) {} 

38.     } 

39.   } 

40.

41. ========== SQL examples ============================= 

42.   SELECT NAME, CONTACT, PHONE 

43.   FROM CUSTOMERS 

44.   WHERE CITY = 'Herndon' 

45.  

46.   SELECT DISTINCT CUSTID 

47.   FROM ORDERS 

48.   ORDER BY CUSTID 

49.  

50.   UPDATE CUSTOMERS 

51.   SET CITY = 'The Hague' 

52.   WHERE CITY = 'Den Haag' 

53.  

54.   DELETE FROM CUSTOMERS 

55.   WHERE LASTYRORDERED < 1960 

56.  

57. ========  transaction : ===================== 

58.  

59.   connection.setAutoCommit ( false ) ; 

60.  

61.   try

62.  

63.   .......executeUpdate ( "UPDATE ....."  ) 

64.   .......executeUpdate ( "INSERT ......"  ) 

65.   ..... 

66.   connection.commit ( ) ; 

67.   } 

68.   catch ( SQLException sex ) 

69.   { 

70.     connection.rollback ( ) ; 

71.   } 

72. ====== database vendor drivers ================ 

73.  

74.   DriverManager.registerDriver 

75.   ( new com.ibm.as400.access.AS400JDBCDriver( ) ); 

76. ... 

77.   conn = DriverManager.getConnection 

78.         ( "jdbc:as400://tokyosys" ); 

79.  

80. ======== 

81.   COM.ibm.db2.jdbc.app.DB2Driver 

82. === DataSource, JNDI ====================== 

83. import java.sql.*; 

84. import javax.sql.*; 

85. import javax.naming.*; 

86. .... 

87. DataSource ds = null

88. .... 

89. try

90. InitialContext jndictx = new InitialContext(); 

91. ds = (DataSource) jndictx.lookup 

92.         ( "java:/DefaultDS" ); 

93. .... 

94. Connection con = null

95. con =  ds.getConnection(); 

96. ... 

97. === jndi.properties ======= 

98. java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory 

99. java.naming.provider.url=localhost:1099 

100.