码迷,mamicode.com
首页 > 数据库 > 详细

JDBC

时间:2015-05-29 17:13:24      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

package com.ocean.san;

import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.sql.CLOB;

public class JDBC {

	private static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
	private static String user = "scott";
	private static String password = "tiger";
	private static Connection conn;

	private static Connection getConn() {

		if (conn == null) {
			try {
				Class.forName("oracle.jdbc.driver.OracleDriver");

				conn = DriverManager.getConnection(url, user, password);

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

	}

	/**
	 * JDBC操作clob类型
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		try {

			PreparedStatement ps3 = JDBC.getConn().prepareStatement(
					"select nvl(max(key)+1,0) key from ex_tab ");
			ps3.executeQuery();
			ResultSet rs1 = ps3.getResultSet();
			int key = 0;
			while (rs1.next()) {

				key = rs1.getInt("key");
			}
			if (ps3 != null) {
				ps3.close();
			}
			// 插入空clob
			PreparedStatement ps = JDBC.getConn().prepareStatement(
					"insert into ex_tab (key,msg) values(?,?)");
			ps.setInt(1, key);
			ps.setClob(2, CLOB.getEmptyCLOB());
			ps.executeUpdate();
			if (ps != null) {
				ps.close();
			}
			// 锁定插入的空clob
			PreparedStatement ps1 = JDBC.getConn().prepareStatement(
					"select msg from ex_tab where key=" + key + "  for update");
			ps1.executeQuery();
			ResultSet rs = ps1.getResultSet();
			Clob colb = null;
			while (rs.next()) {

				colb = rs.getClob("msg");
			}
			if (ps1 != null) {
				ps1.close();
			}
			// 更新clob
			PreparedStatement ps2 = JDBC.getConn().prepareStatement(
					"update  ex_tab set msg=? where key=1 ");
			colb.setString(1, "ooooooooooooooooooooooooooo");
			ps2.setClob(1, colb);
			ps2.executeUpdate();
			if (ps2 != null) {
				ps2.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeConn();
		}

	}

	static void closeConn() {

		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

 

JDBC

标签:

原文地址:http://www.cnblogs.com/ocean-san/p/4538543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!