日期:2014-05-16 浏览次数:20548 次
今天做了一个小的测试,JDBC连接oracle数据库,网上的例子很多,这儿仅做了简单的Java代码测试是否连接成功。前提是要引入ojdbc.jar包。
Java代码如下:
?
package com.learning; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Test { // 连接url private static String url = "jdbc:oracle:thin:@localhost:1521:orcl"; // 用户名 private static String user = "charice"; // 密码 private static String password = "123456"; public static Connection conn; public static PreparedStatement ps; public static ResultSet rs; public static Statement st; // 连接数据库的方法 public static Connection getConnection() { try { // 初始化驱动包 Class.forName("oracle.jdbc.driver.OracleDriver"); // 根据数据库连接字符,名称,密码给conn赋值 conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } return conn; } //测试能否与oracle数据库连接成功 public static void main(String[] args) { /*Test basedao=new Test(); basedao.getConnection(); if(conn==null) { System.out.println("与oracle数据库连接失败!"); }else{ System.out.println("与oracle数据库连接成功!"); } */ query(); } // 查询代码 public static void query() { conn = getConnection(); try { String sql = "select * from t_icpc_userinfo"; st = conn.createStatement(); ResultSet rs = st.executeQuery(sql); System.out.println("最后的查询结果为:"); // 打印结果集 while (rs.next()) { String userid = rs.getString("userid"); String nickname = rs.getString("nickname"); String sex = rs.getString("sex"); String signinfo = rs.getString("signinfo"); System.out.println(userid + " " + nickname + " " + sex + " " + signinfo); } conn.close(); } catch (SQLException e) { System.out.println("查询数据失败"); } } // 删除代码 public static void delete() { conn = getConnection(); String sql = "delete from t_icpc_userinfo where userid = '100001'"; try { st = conn.createStatement(); int count = st.executeUpdate(sql); System.out.println(count); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } // 修改操作 public static void update() { conn = getConnection(); String sql = "update t_icpc_userinfo set signinfo = '你是一个人吗' where userid = '100002'"; try { st = conn.createStatement(); int count = st.executeUpdate(sql); System.out.println(count); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } // 插入操作 public static void insert() { conn = getConnection(); String sql = "insert into t_icpc_userinfo(userid, nickname, sex, signinfo) values('100003', 'wang', '2', '又要测试')"; try { st = conn.createStatement(); int count = st.executeUpdate(sql); System.out.println(count); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }