escaping - java resultset.getstring("col_name") query -
i have simple query regarding resultset.getstring()
method in java jdbc.
suppose value in database column having \
javas escape character e.g. \n
or \t
etc.
when retrieve value getstring()
see 1 more escape character getting added , actual meaning of \n
string literal only.
had unescape java , use properly.
string s= rs.getstring("col_name");
when s
contains `\n':
system.out.println(s)
output:
\n
after unescaping java using apache common stringescapeutils
output:
system.out.println("hi"+s+"hello"); hi hello
my question adding \
before unescaping?? sorry if dumb question.
the jdbc driver no escaping in resultset
. bad if does. @ simple example:
the database table x
contain 1 column value
. there 2 rows: 1 2 character string ('\'
, 'n'
) , 1 witch 1 character string (the newline character). i've added string-length output clarification.
select *, length(value) x; value | length -------+-------- \n | 2 +| 1 |
this table read jdbc:
connection db = drivermanager.getconnection( /* these parameters */ ); statement st = db.createstatement(); resultset rs = st.executequery("select value, length(value) x"); while(rs.next()){ string value = rs.getstring(1); int length = rs.getint(2); system.out.println("length="+length+", value='"+value+"'"); }
you see: no explicit escaping anywhere in code far. , output is:
length=2, value='\n' length=1, value=' '
you see: there still nothing escaped - neither code nor jdbc.
but
things bit murky if mix in java literals: if this:
st.execute("insert x values ('\n')");
then guess happened? have row one character!
length=2, value='\n' length=1, value=' ' length=1, value=' '
this because java compiler translated 2 characters '\n' 1 newline character. hence jdbc driver , database see 1 character.
but if have read userinput , user have typed \
, n
nobody de-escape , row have contained 2 characters.
next step
you say, explicit de-escaping using stringescapeutils
. happen:
- the row 1 character pass unaltered db screen.
- the row 2 characters changed
stringescapeutils
string containing 1 characters. after both row same you.
summary
do not confuse string-literal escaping compiler escaping jdbc (which won't happen).
do not add unnecessary escaping layers.
Comments
Post a Comment