简体   繁体   中英

Insert into sql column more than 8000 chars with line breaks in java

how to insert data into one column in MS-SQL more than 8000 chars with line breaks using java?

I have a software list from psinfo - sorting and converting arraylist to string with StringBuilder and replacing \\n with "' + CHAR(13)+CHAR(10) + '"

I can insert all text with around 15000 chars without CHAR 10 and CHAR 13 but I cannot insert it with new lines, it's inserting only around 8000 chars.

Do you know where is the problem?

I have field software as VARCHAR(MAX)

I have this statement: stmt.executeUpdate(... "',software= CAST('" + software + "' AS varchar(MAX))...);

I would suggest using a PreparedStatement :

PreparedStatement stmt = con.prepareStatement("... software=? ...");
stmt.setString(index, veryLongStringWithNewlines);
stmt.executeUpdate();

This will avoid any issues with characters in the string that conflict with the SQL dialect's syntax for string literals.

(I couldn't figure out what the CAST ... AS would achieve, so I left it out. I'm guessing it was an attempt to deal with the string length or the embedded newlines or something.)

I also recommend to, instead of creating such an SQL expression, add the newlines directly to the string in the Java code and use the result in a parametrized query. To solve this problem and to avoid other problems.

But I was interested in the "why" of this case and did a little testing.

The problem seems to be caused by an implicit cast due to the + string operator. The docs state, that the type with the highest precedence of those types from the operands is returned.

If only varchar(n) operands are included, the operation apparently returns a varchar(m) but no varchar(max) . The maximum for m is 8000 . So the data gets truncated if the result is actually longer than 8000 characters.

+ needs to "see" at least one varchar(max) amongst the operands to return varchar(max) .

SELECT '<put 8000 a's here>' + 'b'

results in '<put 8000 a's here>' (without the 'b' ), whereas

SELECT '<put 8000 a's here>c' + 'b'

results in '<put 8000 a's here>cb' .

To get a result of varchar(max) it's enough to give + one such operand, possibly by convert() .

SELECT '<put 8000 a's here>' + convert(varchar(max), 'b')

results in '<put 8000 a's here>b' , as expected.

So as the lines in the string from the Java program likely never exceeded 8000 characters in length, the + operation gave a varchar(8000) , whereas the whole string, without any operation on it exceeded the 8000 character boundary and was implicitly seen as varchar(max) by SQL Server. That's why all of a sudden the program broke.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM