`

JDBC SQL字符转移

    博客分类:
  • Java
 
阅读更多

An example of this is if you want to issue the following SQL command: 


SELECT * FROM BIRDS  
  WHERE SPECIES='Williamson's Sapsucker' 

In this case, the apostrophe in "Williamson's" is going to cause a problem for the database because SQL will interpret it as a string delimiter. It is not good enough to use the C-style escape \', because that substitution would be made by the Java compiler before the string is sent to the database. 

Different flavors of SQL provide different methods to deal with this situation. JDBC abstracts these methods and provides a solution that works for all databases. With JDBC you could write the SQL as follows: 

Statement statement = // obtain reference to a Statement 
statement.executeQuery( 
  "SELECT * FROM BIRDS  WHERE SPECIES='Williamson/'s Sapsucker' {escape '/'}"); 

The clause in curly braces, namely {escape '/'}, is special syntax used to inform JDBC drivers what character the programmer has chosen as an escape character. The forward slash used as the SQL escape has no special meaning to the Java compiler; this escape sequence is interpreted by the JDBC driver and translated into database-specific SQL before the SQL command is issued to the database. 

 

 

 

例外一种解决方案:使用 PreparedStatement

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics