Step By Step(Java JDBC篇) (四)

2014-11-24 03:19:38 · 作者: · 浏览: 5
on,

6 ClassNotFoundException {

7 Class.forName("oracle.jdbc.driver.OracleDriver");

8 Properties conProps = new Properties();

9 conProps.put("user", "sys");

10 conProps.put("password", "helloworld");

11 conProps.put("internal_logon", "sysdba");

12 return DriverManager.getConnection(

13 "jdbc:oracle:thin:@//192.168.1.101:1526/OraHome", conProps);

14 }

15 public static void main(String[] args) throws ClassNotFoundException {

16 Connection conn = null;

17 Statement stmt = null;

18 PreparedStatement pstmt = null;

19 ResultSet rs = null;

20 try {

21 conn = getConnection();

22 stmt = conn.createStatement();

23 stmt.executeUpdate(EMPLOYEE_TABLE);

24 stmt.executeUpdate("insert into MyEmployees3(id, firstName) values(100, 'A')");

25 stmt.executeUpdate("insert into MyEmployees3(id, firstName) values(200, 'B')");

26 String sql = "select id, firstName,lastName from MyEmployees3";

27 rs = stmt.executeQuery(sql);

28 // extract data from the ResultSet

29 while (rs.next()) {

30 int id = rs.getInt(1);

31 String firstname = rs.getString(2);

32 String lastname = rs.getString(3);

33 System.out.println("id = " + id);

34 System.out.println("firstname = " + firstname);

35 if (lastname == null)

36 System.out.println("the lastname is null.");

37 System.out.println("lastname = " + lastname);

38 System.out.println("---------------");

39 }

40 rs.close();

41 //动态绑定查询参数

42 sql = "select id from MyEmployees3 where firstName = ";

43 pstmt = conn.prepareStatement(sql);

44 ParameterMetaData paramMetaData = pstmt.getParameterMetaData();

45 if (paramMetaData == null) {

46 System.out.println("db does NOT support ParameterMetaData");

47 } else {

48 System.out.println("db supports ParameterMetaData");

49 int paramCount = paramMetaData.getParameterCount();

50 System.out.println("paramCount=" + paramCount);

51 }

52 pstmt.setString(1, "A");

53 rs = pstmt.executeQuery();

54 while (rs.next()) {

55 int id = rs.getInt(1);

56 System.out.println("id = " + id);

57 System.out.println("---------------");

58 }

59 } catch (Exception e) {

60 e.printStackTrace();

61 } finally {

62 try {

63 stmt.execute("drop table MyEmployees3");

64 rs.close();

65 pstmt.close();

66 stmt.close();

67 conn.close();

6