-1

I am new to use mysql with JAVA API. Now the way I send query or update is that I simply create a String containing all lines, and then pass it to executeQuery() or executeUpdate(). I found it annoy because to pass variables from Java I would have to end quote put in variable another quote, and I had to work carefully around spaces and inner quotes.

I was wondering:

  1. Is there a better way to send queries or updates? I tried to do some research on reasons for PreparedStatement but didn't learn much.
  2. Is there a better way to pass variables?

Also, if you have got some advice for newbies please also include it. Thanks

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
verticese
  • 273
  • 1
  • 4
  • 11
  • 1
    `I tried to do some research on reasons for PreparedStatement but didn't learn much.` - keep looking, that is the way to go. There are examples in the forum or on the web. For example did you look at the posting under the `Related` heading on the right side of this page? We can't guess what you find confusing about the examples you have already found. – camickr Jun 07 '13 at 03:56
  • 3
    [Example of `PreparedStatement` for insert](http://stackoverflow.com/a/11441591/1065197) Hint: you can do similar for `UPDATE`, `DELETE` and `SELECT` statements. – Luiggi Mendoza Jun 07 '13 at 03:59
  • And [just another example](http://stackoverflow.com/a/15122018/1065197) – Luiggi Mendoza Jun 07 '13 at 04:00

1 Answers1

1

Option 1: Prepared statement method should work fine.

PreparedStatement pstmt = null;
Stirng studentUpdate = "UPDATE student SET grade = ? where id = ?";
try {
    pstmt = conn.prepareStatement(studentUpdate);
    pstmt.setString(1, "A");
    pstmt.setInt(2, 34);
    pstmt.executeUpdate();

} catch(Exception a) {
    a.printStackTrace();
}

Option 2: Create a stored procedure in your database The java stored Procedure talks extensively about this (I used it when I had single quote problems (') with my strings ).

Sunny Patel
  • 535
  • 2
  • 5
  • 13
  • "Option 2" really includes "Option 1", because you'd want to use a `PreparedStatement` to pass parameters to your stored procedures. – Joachim Sauer Jun 07 '13 at 08:54
  • Yes that's right. you would have to use Stored Procedures for both. I should mention that option 2 would just pass the values to DB where the logic is stored. and option 1 would pass the statement it's self. – Sunny Patel Jun 07 '13 at 10:14