Pete Freitag Pete Freitag

Prepared Statements with JDBC

Published on March 18, 2005
By Pete Freitag
java

To prevent SQL Injection Hacking with JDBC, you simply just need to use Prepared Statements, this is pretty easy to, just use a PreparedStatement object instead of a Statement Object, in your SQL replace your variables with ?'s, and use the setString, setInt, etc methods on the perpared statement object.

PreparedStatement st = (PreparedStatement)connection.createStatement();
st.setString(1, "Arg 1");
st.setString(2, "Arg 2");
String sql = "SELECT foo FROM bar WHERE a = ? AND b = ?";

One thing to note is that the indexes start at 1, not 0



jdbc java databases

Prepared Statements with JDBC was first published on March 18, 2005.

If you like reading about jdbc, java, or databases then you might also like:

Weekly Security Advisories Email

Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).

Comments

Hello Sean. What is the idea of the project?! At the moment, there are plenty of very promising O/R frameworks. You've got JDO and EJB3.0 whereas the latter one will be more or less a subset of the first one. However, EJB3.0 will also utilize Java 5 annotations. If you want to look even further, then have a look on JBoss and Hibernate. Both projects are linked together and JBoss is going to realize EJB3.0 based on Hibernate as the working horse for the persistence. Hibernate, however, can also be used in any other Java program, also stand-alone.
Cheers, Daniel
by Daniel on 03/19/2005 at 2:58:39 AM UTC
can u tell me if it is write "SELECT ? FROM tablename WHERE user=?"
if not then how can we write variable after SELECT
by megha on 06/15/2005 at 5:08:09 AM UTC
im having trouble using prepared statements to insert information from a form into a database. it works fine when the input is a number, but when it is a string (say a name or something) it crashes. and says that 'harry' is not allowed in this context, only constants variables or expressions allowed here'

my field is a text field in the database, so i don't know what could be wrong except for my prepared statement. i followed it right out of a (sigh) dreamweaver tutorial.. can you help me out?

<%
Driver DriverPrepared1 = (Driver)Class.forName(MM_wddatabase_DRIVER).newInstance();
Connection ConnPrepared1 = DriverManager.getConnection(MM_wddatabase_STRING,MM_wddatabase_USERNAME,MM_wddatabase_PASSWORD);
PreparedStatement Prepared1 = ConnPrepared1.prepareStatement("INSERT INTO dbo.AlternateIDTable (WHMNID, IDtype, IDvalue) VALUES ("+ Prepared1__animal + ","+ Prepared1__altid + ","+ Prepared1__alt + ") ");
Prepared1.executeUpdate();
%>
by megan on 07/07/2005 at 2:40:44 PM UTC