[英]Split the string 3 times and inserted into database - Java
它的抓取工具,同時運行獲取更多長度的字符串值,如152263
。 我想將此字符串值插入 db (SQL - nvarchar(max)) 中,整個長度不適合單個列( after 42600 its truncated
),因此我更改表,再添加一列並插入值。
if (fullText.length() > 42600) {
preparedStatement.setString(35, fullText.substring(0, 42500));
preparedStatement.setString(36, fullText.substring(42500, fullText.length()));
} else {
preparedStatement.setString(35, fullText);
preparedStatement.setString(36, "");
}
上面的一個可以完美地用於 2 列。 在某些情況下,它的退出超過兩列讓我知道如何將其分成 3 次(等於字符串長度)並存儲到 sql db 中的 3 列中。
if (fullText.length() > 42600) {
preparedStatement.setString(35, fullText.substring(0, 42500));
if (fullText.length() > 85000) {
preparedStatement.setString(36, fullText.substring(42500, 85000));
preparedStatement.setString(37, fullText.substring(85000, fullText.length()));
} else {
preparedStatement.setString(36, fullText.substring(42500, fullText.length()));
}
} else {
preparedStatement.setString(35, fullText);
preparedStatement.setString(36, "");
preparedStatement.setString(37, "");
}
根據給定的限制檢查長度,並從最長到最短的范圍進行比較。 不確定是否要在空列中存儲 "" 或 NULL
String first = "";
String middle = "";
String last = "";
if (fullText.length > SPLIT_LIMIT * 2) {
last = fullText.substring(SPLIT_LIMIT * 2 + 1);
}
if (fullText.length > SPLIT_LIMIT) {
middle = fullText.substring(SPLIT_LIMIT + 1, SPLIT_LIMIT * 2);
first = fullText.substring(0, SPLIT_LIMIT * 2);
} else {
first = fullText;
}
preparedStatement.setString(35, first);
preparedStatement.setString(36, middle);
preparedStatement.setString(37, last);
這是一個使用循環來靈活計算列數的解決方案:
String text = "";
int idCounter = 35;
while(text.length() > 42600){
preparedStatement.setString(idCounter, text.substring(0, 42600));
text = text.substring(42601,text.length());
idCounter++;
}
preparedStatement.setString(idCounter, text);
(未測試)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.