jdbc clob 操作

JdbcUtil

public final class JdbcUtil {

	private static String url = "jdbc:mysql://localhost:3306/blobtest";
	private static String user = "root";
	private static String password = "root";

	private JdbcUtil() {

	}

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);
	}

	public static void free(ResultSet rs, Statement stmt, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null) {
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}

 ClobTest

public class ClobTest {

	public static void main(String[] args) throws Exception {
		ClobTest.read();
	}
	
	static void create() throws Exception{
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtil.getConnection();
			String sql = "INSERT INTO clob(clob) VALUES (?) ";
			ps = conn.prepareStatement(sql);
			File file = new File("src/cn/lichaozhang/jdbc/Base.java");
			Reader reader = new BufferedReader(new FileReader(file));
			ps.setCharacterStream(1, reader, file.length());
			int i = ps.executeUpdate();
			System.out.println(i);
			reader.close();
		} finally {
			JdbcUtil.free(null, ps, conn);
		}
	}
	
	static void read() throws Exception {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			st = conn.createStatement();
			rs = st.executeQuery("SELECT clob FROM clob");
			while (rs.next()) {
				Clob clob = rs.getClob(1);
				Reader reader = clob.getCharacterStream();
				File file = new File("Base_bak.java");
				Writer writer = new BufferedWriter(new FileWriter(file));
				char[] buff = new char[1024];
				for (int i = 0; (i = reader.read(buff)) != -1;) {
					writer.write(buff, 0, i);
				}
				writer.close();
				reader.close();
			}
		} finally {
			JdbcUtil.free(rs, st, conn);
		}
	}
}

  

你可能感兴趣的:(sql,mysql,jdbc)