當前位置:首頁 » 編程語言 » javasqlclob轉string
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

javasqlclob轉string

發布時間: 2022-05-04 04:18:22

1. 如何把clob類型數據變成string類型的數據

給你段參考代碼,讀取clob數據

import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class TestClobOut {
public static void main(String args[]){
String data;
Reader inStream=null;
//獲得資料庫連接
Connection con = ConnectionFactory.getConnection();//ConnectionFactory類是另外定義的,不必糾結
con.setAutoCommit(false);
Statement st = con.createStatement();
//不需要「for update」
ResultSet rs = st.executeQuery("select CLOBATTR from TESTCLOB where ID=1");
if (rs.next())
{
java.sql.Clob clob = rs.getClob("CLOBATTR");
inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
//data是讀出並需要返回的數據,類型是String
data = new String(c);
inStream.close();
}
inStream.close();
con.commit();
con.close();
}
}

2. oracle資料庫CLOB類型怎麼轉換為String

給你段參考代碼,讀取clob數據

import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class TestClobOut {
public static void main(String args[]){
String data;
Reader inStream=null;
//獲得資料庫連接
Connection con = ConnectionFactory.getConnection();//ConnectionFactory類是另外定義的,不必糾結
con.setAutoCommit(false);
Statement st = con.createStatement();
//不需要「for update」
ResultSet rs = st.executeQuery("select CLOBATTR from TESTCLOB where ID=1");
if (rs.next())
{
java.sql.Clob clob = rs.getClob("CLOBATTR");
inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
//data是讀出並需要返回的數據,類型是String
data = new String(c);
inStream.close();
}
inStream.close();
con.commit();
con.close();
}
}

3. oracle clob類型不能再select查詢的時候就給轉換成String類型嗎

clob不可以直接insert。。。。。。。使用java.sql.Clob/Blob導入

4. java將string插入到類型為clob的ORACLE庫中

1:首先:寫個連接資料庫的類,裡面有返回mysq, oracle連接的方法

public Connection getConn(String flag){
Connection con=null;
try
{
if(flag.equals("1"))
{
Class.forName(「oracle.jdbc.driver.OracleDriver」);
con = DriverManager.getConnection(「jdbc:oracle:thin:@IP:1521:資料庫名字」,"name","password");
}
if(flag.equals("2"))
{
Class.forName("org.gjt.mm.mysql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/資料庫名?user=用戶名&password=密碼&useUnicode=true&characterEncoding=GBK");
}

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

2:執行插入操作

public void setData() {
conn = new Conn();
try {
String sqlfrom = "select p.id,p.content from table p order by p.id ";
String sqlinsert = "insert into table values(?,?)";
con = conn.getConn("2");
stmt = con.createStatement(); //從mysql取出大欄位
rs = stmt.executeQuery(sqlfrom);
con = conn.getConn("1");
PreparedStatement pstmt = con.prepareStatement(sqlinsert); //向oracle中插入大欄位
int i = 0;
while (rs.next()) {
pstmt.setInt(1, rs.getInt(1));
pstmt.setClob(2, oracle.sql.CLOB.empty_lob());
pstmt.executeUpdate(); //插入時將大欄位設為空
this.updateOne(con,rs.getInt(1),rs.getString(2)); // 這里調用然後更新這個大欄位
}

rs.close(); //關閉相關連接
pstmt.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
try
{
con.rollback();
} catch (Exception e1) {
System.out.println("回滾出現異常!");
e1.printStackTrace();
}
}
}
3:該方法實現對應大欄位記錄的更新
public void updateOne(Connection con,int id, String content) {
String str = "select t.content from table t where t.id=" + id+ " for update";
try {
// 注意:存取操作開始前,必須用setAutoCommit(false)取消自動提交,否則Oracle將拋出「讀取違反順序」的錯誤。
con.setAutoCommit(false);
stmt = con.createStatement();
ResultSet rs_clob = stmt.executeQuery(str);
while ( rs_clob .next()) {
/* 取出clob數據*/
oracle.sql.CLOB clob = (oracle.sql.CLOB) rs_clob .getClob(1);
/* 向clob中寫入數據*/
clob.putString(1, content);
}
stmt.close();
con.commit();
con.setAutoCommit(true);
con.close();
} catch (Exception e) {
e.printStackTrace();
try
{
con.rollback();
} catch (Exception e1) {
System.out.println("回滾出現異常!");
e1.printStackTrace();
}
}
}

現在就完成了一行記錄的更新。

4:讀clob欄位以String 的形式返回(當然也可以將讀到的內容寫入文件,大家改一下就可以了)
/**
* 讀clob欄位
* @param con
* @param id
* @return
*/
public String readClob(Connection con,int id)
{
String content="";
try
{
con.setAutoCommit(false);
stmt=con.createStatement();
ResultSet rs_clob=stmt.executeQuery("select t.content from table t where t.id="+id);
oracle.sql.CLOB contents=null;
while (rs_clob.next())
{ // 取出CLOB對象
contents= (oracle.sql.CLOB) rs_clob.getClob(1);
}
BufferedReader a = new BufferedReader(contents.getCharacterStream()); //以字元流的方式讀入BufferedReader
String str = "";
while ((str = a.readLine()) != null) {
content = content.concat(str); //最後以String的形式得到
}
con.commit();
/*
BufferedWriter out = new BufferedWriter(new FileWriter("e:/test.txt"));
out.write(content); //寫入文件
out.close(); */
con.setAutoCommit(true);
con.close();
}catch(Exception e)
{
System.out.println("出現異常");
e.printStackTrace();
try
{
con.rollback();
}
catch (Exception e1)
{
System.out.println("回滾出現異常!");
e1.printStackTrace();
}
}
return content;
}

5. String 轉化為 java.io.Clob 對象

要先將原來的數據的clob欄位置為空,然後更新,用這個:

conn = DAOFactory.getInstance().getConnection();
// 事務處理
conn.setAutoCommit(false);

// 先把clob欄位content置空,content為clob欄位
String sql = "update " + table + " set content=empty_clob()";
stmt = conn.createStatement();
stmt.executeUpdate(sql);

// 從資料庫中取出插入的clob欄位
sql = "select content from " + table + " for update";
rs = stmt.executeQuery(sql);
if(rs.next()) {
// 給clob數據重新賦值,然後更新到資料庫中
Clob clob = rs.getClob(1);
clob.setString(1, content);
sql = "update " + table + " set content=? where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setClob(1, clob);
pstmt.setString(2, id);
pstmt.executeUpdate();
}

// 事務提交
conn.commit();
conn.setAutoCommit(true);

補充:

Clob有點特殊,它是一個資料庫相關的介面,沒法實例化, 你可以通過SerialClob來實例化,這個我沒用過。

api上這樣寫到:

public SerialClob(char[] ch)
throws SerialException,
SQLException按照給定 char 數組的序列化形式構造一個 SerialClob 對象。
新的 SerialClob 對象使用 char 數組中的數據進行初始化,因此允許未連接 RowSet 對象無需接觸數據源即可建立序列化的 Clob 對象。

參數:
ch - 表示要序列化的 Clob 對象的 char 數組

你試試吧

6. JAVA讀取Oracle資料庫Clob欄位轉換成String問題

如果使用oracle的話,直接將clob欄位讀取為string;也就是下面這一行:
clob
=
(oracle.sql.clob)
rs.getobject(1);
可以直接寫成
string
str
=
rs.getstring(1);

7. 資料庫中欄位的類型是blob,頁面傳入的類型是string,怎麼轉換才能插入進去

存入:
byte[] buffer = System.Text.Encoding.Default.GetBytes(你的數據);
OracleCommand cmd = new OracleCommand(你的sql語句, 你的連接);
cmd.Parameters.Add("你的欄位", OracleType.Blob);
cmd.Parameters[0].Value = buffer;
cmd.ExecuteNonQuery();
讀取:
OracleLob clob = OracleLob.Null;
OracleCommand command = new OracleCommand(你的select語句, 你的連接);
OracleDataReader reader = command.ExecuteReader();
while(reader.Read())
{
clob = reader.GetOracleLob(你的列名);
byte[] buffer = (byte[])reader["你的欄位"];
string format = System.Text.Encoding.Default.GetString(buffer);//轉換成string
//以後想怎麼處理format就看你了,你也可以把buffer轉換成你想要的類型
}

去網上下相關的包吧,在JSP裡面寫的也一樣的

8. 怎麼把一個String轉成CLOB

既然你是從資料庫取出CLOB欄位,那麼不用resultset那是用什麼取出的。
如果從資料庫裡面取出的是CLOB欄位,為什麼會變成String類型呢。

String轉CLOB,下面是個例子

public class TestDB {
public static void main(String[] args) {
try {

/** Loading the driver*/

Class.forName("com.oracle.jdbc.Driver");

/** Getting Connection*/
Connection con = DriverManager.getConnection("jdbc:oracle://localhost:3306/test","test","test");

PreparedStatement pstmt = con.prepareStatement("insert into Emp(id,name,description)values(?,?,?)");
pstmt.setInt(1,5);
pstmt.setString(2,"Das");
// Create a big CLOB value...AND inserting as a CLOB
StringBuffer sb = new StringBuffer(400000);

sb.append("This is the Example of CLOB ..");
String clobValue = sb.toString();
pstmt.setString(3, clobValue);
int i= pstmt.executeUpdate();
System.out.println("Done Inserted");
pstmt.close();
con.close();

// Retrive CLOB values
Connection con = DriverManager.getConnection("jdbc:oracle://localhost:3306/test","test","test");
PreparedStatement pstmt = con.prepareStatement("select * from Emp where id=5");
ResultSet rs = pstmt.executeQuery();
Reader instream = null;
int chunkSize;
if(rs.next()){
String name = rs.getString("name");
java.sql.Clob clob = result.getClob("description")
StringBuffer sb1 = new StringBuffer();

chunkSize = ((oracle.sql.CLOB)clob).getChunkSize();
instream = clob.getCharacterStream();
BufferedReader in = new BufferedReader(instream);
String line = null;
while ((line = in.readLine()) != null) {
sb1.append(line);
}
if(in != null){
in.close();
}

String clobdata = sb1.toString(); // this is the clob data converted into string

}

} catch (Exception e) {

e.printStackTrace();
}
}
}

9. java String類型和blob類型轉換

如果你的數據真的是 String ,那按理就是用 Clob 嘛。
Blob 主要用於二進制內容,比如圖片,附件。

如果保持資料庫表結構不變的話,用 blob 也行,但你需要在讀取和寫入兩頭明確地指定相同的字元集,否則讀取這個還原過程會得到不到期望的結果。只要我們用支持這種字元的字元集理論上來說,只要編碼和解碼的過程使用相同的字元集就不會失真,如果字元集本身不支持這個字元(比如你拿一個只有康熙字典中才有的古漢字用 GB2312 字元集去處理就會失真,而用 UTF8 就可能正常,因為只要這個字元真的能被輸入法錄入到電腦中基本上它就已經表示有辦法能處理它)。

PreparedStatement 中有 setBlob (JDBC 4.0) 或 setBinaryStream (早期) 方法。但你需要測試你使用的驅動程序是什麼版本的與資料庫是否匹配。

10. Spring+Mybatis類型轉換的問題,oracle資料庫中有一個clob類型,怎樣在查詢以後轉換為String類型

首先你的思路就錯的,不可能轉換成string

  1. 把大對象讀進byte[]

public byte[] function(Connection connection,所需參數) throws EMPException{

PreparedStatement ps = null;
ResultSet rs = null;
byte[] data = null;
try {
.....省略
while (rs.next()) {
oracle.sql.CLOB clob= (oracle.sql.CLOB) rs.getClob("大對象的欄位名");
InputStream inStream =clob.getBinaryStream();
long nLen = clob.length();
int nSize = (int) nLen;
data = new byte[nSize];
inStream.read(data);
inStream.close();
connection.commit();

}
} catch (SQLException e) {
EMPLog.log(this.getClass().getName(), EMPLog.INFO, 0, e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (ps != null) {
ps.close();
ps = null;
}
} catch (SQLException e) {
EMPLog.log(this.getClass().getName(), EMPLog.INFO, 0, e
.toString());
}
}
return data;
}

2.直接在頁面上將對象讀到頁面上

<form action="">
<%

response.setContentType("image/jpg");
response.setHeader("Content-Transfer-Encoding","base64");
ServletOutputStream toClient = response.getOutputStream();
out.clear();
out = pageContext.pushBody();
ByteArrayInputStream in = new ByteArrayInputStream(data);
int len;
byte[] buf = new byte[1024];
while ((len = in.read(buf, 0, 1024)) != -1) {
toClient.write(buf, 0, len);
}
toClient.flush();
toClient.close();
%>
</form>