JDBC - prepareStatement - How to use it?

I saw this example somewhere:

 rs = connection.prepareStatement("select * from table").executeQuery();

      

Can I use this format if I want to run a query like this " Select * from table where column =" hello " "?

The way I usually use the prepareStatement object is something like this:

        String sql = "select * from adresa where column = ?";
        PreparedStatement pre = con.prepareStatement(sql);
        pre.setString(1, i);
        rs = pre.executeQuery();

      

Later Edit:

I do not understand. Pascal Tivent wrote that I can use the short version with In parameters, but Liu says it is not possible. :) Anw, using the Pascal version, I get this error: void cannot be dereferenced

+2


source to share


4 answers


You can only use the first form if there are no bind variables (question marks) in the request. This is just a shortened version of what you posted.



Also, if you are using the shorthand form, you will not be able to reuse the PreparedStatement object.

+1


source


You can of course use a string variable for the request where u puts dynamic data in ur and runs it.



rs = connection.prepareStatement (variable) .executeQuery ();

0


source


Long form is common, but prepared statements can be precompiled by db and if used correctly will help prevent SQL injection.

Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
 conn = getConn();
 ps = conn.prepareStatement("select * from x where y = ? "); //note no sb.append() or +'s, to helps prevent sql injection
 ps.setLong(1, 12l);
 rs = ps.executeQuery();

 while (rs.next()) {
 ... act ...
 }
} catch ( Exception e) {
} finally {
 if (rs != null) rs.close(); 
 if (ps != null) ps.close();
 if (conn != null) conn.close();
}

      

Who said java was verbose. :)

0


source


Here's an example using this interface:

static final String USER = "root";
            static final String PASS = "newpass";

            Connection conn = DriverManager.getConnection(myUrl, USER, PASS);

            // create a sql date object so we can use it in our INSERT statement
            Calendar calendar = Calendar.getInstance();
            java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());

            // the mysql insert statement
            String query = " insert into students (ID, last_name, first_name, birthday, hometown)"
                    + " values (?, ?, ?, ?, ?)";

            // create the mysql insert preparedstatement
            PreparedStatement preparedStmt = conn.prepareStatement(query);
            preparedStmt.setInt(1, 808027);
            preparedStmt.setString(2, "Davis");
            preparedStmt.setString(3, "Felicita");
            preparedStmt.setDate(4, startDate);
            preparedStmt.setString(5, "Venice");

            // execute the preparedstatement
            preparedStmt.execute();

            conn.close();

      

0


source







All Articles