当前位置:首页 > 开发 > 数据库 > 正文

JDBC链接Oracle参考代码

发表于: 2010-07-16   作者:cuisuqiang   来源:转载   浏览:
摘要: package com.gr.util; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.T
package com.gr.util;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
public class ConnectionManager {
	public static void main(String[] args) {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			String url = "jdbc:oracle:thin:@localhost:1521:cui";
			Connection conn = DriverManager.getConnection(url, "cui", "cui");
			System.out.println("链接成功:" + conn.toString());
			conn.setAutoCommit(true); // 设置自动提交

			// 调用带参数有返回值的存储过程
			// 注意这里参数的位置和类型必须和存储过程里定义的一致,输出参数进行注册,而输入参数进行赋值
			CallableStatement cstmp = conn
					.prepareCall("{call insert_class(?,?)}");
			cstmp.registerOutParameter(1, Types.INTEGER);
			cstmp.setString(2, "存储过程组");
			cstmp.execute();
			// 没有返回值
			// cstmp.executeUpdate();
			int newId = cstmp.getInt(1);
			System.out.println(newId);

			// 查询,带有分页语句
			String sql_select = "SELECT * FROM (SELECT A.*, ROWNUM RN FROM (SELECT * FROM classes) A WHERE ROWNUM <= ?)WHERE RN >= ?";
			PreparedStatement pstmt_sel = conn.prepareStatement(sql_select);
			pstmt_sel.setInt(1, 4);
			pstmt_sel.setInt(2, 3);
			ResultSet rs = pstmt_sel.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getInt("id") + " "
						+ rs.getString("classname"));
			}

			// 增加
			String sql_insert = "insert into classes values(class_seq.nextval,?)";
			PreparedStatement pstmt_add = conn.prepareStatement(sql_insert);
			pstmt_add.setString(1, "JDBC测试");
			int result_insert = pstmt_add.executeUpdate();
			System.out.println(result_insert);

			// 删除
			String sql_delete = "delete from classes where id=?";
			PreparedStatement pstmt_del = conn.prepareStatement(sql_delete);
			pstmt_del.setInt(1, 6);
			int result_delete = pstmt_del.executeUpdate();
			System.out.println(result_delete);

			// 修改
			String sql_update = "update classes set classname=? where id=?";
			PreparedStatement pstmt_mod = conn.prepareStatement(sql_update);
			pstmt_mod.setString(1, "FBI组");
			pstmt_mod.setInt(2, 7);
			int result_update = pstmt_mod.executeUpdate();
			System.out.println(result_update);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

JDBC链接Oracle参考代码

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号