获取数据库连接

-------------------------------oracle--------------------------------
驱动:oracle.jdbc.driver.OracleDriver
url:jdbc:oracle:thin:@host:port:dbname 例:jdbc:oracle:thin:@192.168.1.110:1521:dbOracle
port:端口号,默认是1521
---------------------------sql server---------------------------------
驱动:com.microsoft.jdbc.sqlserver.SQLServerDriver
url:jdbc:microsoft:sqlserver://host:port;databasename=dbname 例:jdbc:sqlserver://192.168.1.111:1433;databasename=dbSql
port:端口号,默认是1433
-------------------------------mysql--------------------------------
驱动:org.gjt.mm.mysql.Drivercom.mysql.jdbc.Driver
url:jdbc:mysql://host:port/dbname   例:jdbc:mysql://192.168.1.112:3306/dbMysql
port:端口号,默认3306
 1     @Test
 2     public void testOracle(){
 3         String driverurl = "jdbc:oracle:thin:@192.168.1.110:1521:dbOracle";
 4         String user = "user";
 5         String password = "password";
 6         Connection conn = null;
 7         Statement stmt = null;
 8         ResultSet rs = null;
 9         try {
10             Class.forName("oracle.jdbc.driver.OracleDriver");
11             conn = DriverManager.getConnection(driverurl, user, password);
12             String sql = "select * from tab_user";
13             stmt = conn.createStatement();
14             rs = stmt.executeQuery(sql);
15             while(rs.next()){
16                 System.out.print(rs.getInt("userid"));
17                 System.out.print(" ;"+rs.getString("username"));
18                 System.out.println();
19             }
20         } catch (ClassNotFoundException e) {
21             System.out.println("未找到类");
22             e.printStackTrace();
23         } catch (SQLException e) {
24             System.out.println("获取连接失败");
25             e.printStackTrace();
26         }finally{
27             try {
28                 if(rs != null) rs.close();
29                 if(stmt != null) stmt.close();
30                 if(conn != null) conn.close();
31             } catch (SQLException e) {
32                 e.printStackTrace();
33             }
34         }
35     }

 

posted @ 2012-12-21 20:08  Gnight  阅读(415)  评论(0编辑  收藏  举报