SQL injection attacks (SQLIAs) aim at exploiting vulnerabilities in web applications in order to execute malicious SQL commands. It is established that prepared statements are resilient to SQLIAs, and thus, developers are advised to use them when constructing SQL queries as opposed to applying string concatenation operations. Unfortunately, this recommended programming practice is not as pervasive as it should be. This paper addresses this shortcoming by presenting SQL injection Prevention by Input Labeling (SQLPIL), an effective, light, and fully automated tool that leverages prepared statements to prevent SQLIAs at runtime. Given a Java program in which SQL queries are built as strings, SQLPIL dynamically transforms the strings into secure prepared statements right before their execution, thus guaranteeing that malicious input will always be treated as data and never as SQL commands. We empirically evaluated our Java implementation of SQLPIL using a benchmark that includes five JSP commercial applications, a number of legitimate queries, and a number of attacks of representative types. The results were promising as all attacks were prevented, and all legitimate runs executed successfully; in other words, the technique exhibited no false alarms when applied on typical applications. Also, the runtime cost was acceptable, assuming typical settings. Copyright © 2015 John Wiley & Sons, Ltd.