java连接oracle的简单实例

连接oracle的时候,要导入oracle驱动的jar包。

连接的时候,有statement和preparedstatement两种,从代码中可以看出不同。

example:

 1 package com.jdbc.oracle;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 import java.sql.Statement;
 9 
10 public class cn1 {
11 
12     /**
13      * @param args
14      */
15     public static void main(String[] args) {
16         Connection conn = null;
17         //Statement stmt = null;
18         PreparedStatement ps = null;
19         ResultSet rs = null;
20         int rowcount = 0;
21         
22         try {
23             //注册数据库驱动程序为Oracle驱动
24             Class.forName("oracle.jdbc.driver.OracleDriver");
25         } catch (ClassNotFoundException e) {
26             //这样写是为了方便调试程序,出错打印mydb()就知道在什么地方出错了
27             e.printStackTrace();
28             System.err.println("mydb(): " + e.getMessage());
29         }
30         
31         try {
32             conn = DriverManager.getConnection("jdbc:oracle:thin:@172.21.1.11:1524:vasd", "chnlmgr", "chnlmgr");
33         } catch (SQLException e) {
34             System.err.println("conn:"+e.getMessage());
35         }
36         
37         if (conn != null) {
38             System.out.println("connection successful");
39         } else {
40             System.out.println("connection failure");
41         }
42         
43         /*
44         try {
45             stmt = conn.createStatement();
46         } catch (SQLException e) {
47             e.printStackTrace();
48         }*/
49         
50         try {
51             //rs = stmt.executeQuery("select * from PO_USER_BASE_INFO where username='guojing'");
52             StringBuffer sql = new StringBuffer();
53             sql.append("select * from PO_USER_BASE_INFO where ");
54             sql.append("username = ?");
55             ps = conn.prepareStatement(sql.toString());
56             ps.setString(1, "guojing");
57             rs = ps.executeQuery();
58             while (rs.next()) {
59                 System.out.println(rs.getString("USERNAME"));
60             }
61             
62             rs.close();
63             //stmt.close();
64             ps.close();
65             conn.close();
66         } catch (SQLException e) {
67             e.printStackTrace();
68         }
69         
70     }
71 }

 

posted @ 2013-08-21 16:27  幻星宇  阅读(1593)  评论(0编辑  收藏  举报