Java JDBC How to - Select data from MySQL database using PreparedStatement








Question

We would like to know how to select data from MySQL database using PreparedStatement.

Answer

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//from   ww w  .  j  a va2 s  .  c o m
public class Main {
  public static void main(String[] args) throws Exception {
    Connection dbConnection = null;
    String myConnectionString = "";
    myConnectionString = "jdbc:mysql://192.168.1.3:3306/mytestdb";
    dbConnection = DriverManager.getConnection(myConnectionString, "root",
        "whatever");
    PreparedStatement stmt = dbConnection
        .prepareStatement("SELECT * FROM jdbctest");
    ResultSet rs = stmt.executeQuery();
    int i = 0;
    int j = 0;
    String s = "";
    while (rs.next()) {
      i++;
      j = rs.getInt("id");
      s = rs.getString("textcol");
    }
    System.out.println(String.format("Finished reading %d rows.", i));
    rs.close();
    stmt.close();
    dbConnection.close();
  }
}

Table

CREATE TABLE `jdbctest` (
  `id` int(11) DEFAULT NULL,
  `textcol` varchar(6) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;