Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Never build SQL queries manually. Always have the query built with parameters and then, pass the parameters to the prepared statement.
Example of good use of Java and SQL queries with a parameter:
PreparedStatementstatement=connection.prepareStatement("select * from mytable where name = ?");statement.setString(1,name);ResultSetresultSet=statement.executeQuery();
publicclassNotCompliant{@GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)@ResponseBodypublicList<Server>sort(@RequestParamStringcolumn)throwsException{List<Server>servers=newArrayList<>();try(varconnection=dataSource.getConnection()){try(varstatement=connection.prepareStatement("select id, hostname, ip, mac, status, description from SERVERS where status <> 'out of order' order by "+column)){try(varrs=statement.executeQuery()){while(rs.next()){Serverserver=newServer(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6));servers.add(server);}}}}returnservers;}}
publicclassNotCompliant{publicStringdoStuff(){Stringquery1="SELECT attr FROM table WHERE id="+idToSearch;Stringquery2=String.format("SELECT attr FROM table WHERE id=%d",idToSearch);Stringquery3="UPDATE table SET attr="+idToSet+" WHERE id="+idToSearch;Stringquery4="DELETE FROM table WHERE id="+idToSearch;}}
Compliant Code Examples
publicclassNotCompliant{publicStringdoStuff(){PreparedStatementstatement=connection.prepareStatement("SELECT attr FROM table WHERE id = ?");statement.setString(1,idToSearch);ResultSetresultSet=statement.executeQuery();}publicvoiddoOtherStuff(){String.format("Framework update return empty result set for (%s, %s)",key.handle(),key.version()));}}
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- java-security # Rules to enforce Java security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines