Java JDBC How to - Store and retrieve a boolean value in a varchar field using JDBC








Question

We would like to know how to store and retrieve a boolean value in a varchar field using JDBC.

Answer

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//w w  w .ja v  a2 s  . c om
public class Main {
  public static void main(String[] args) throws ClassNotFoundException,
      SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(
        "jdbc:mysql://localhost/booltest", "booltest", "booltest");
    conn.prepareStatement(
        "create table booltest (id bigint, truefalse varchar(10));").execute();
    PreparedStatement stmt = conn
        .prepareStatement("insert into booltest (id, truefalse) values (?, ?);");
    stmt.setLong(1, (long) 123);
    stmt.setBoolean(2, true);
    stmt.execute();
    stmt.setLong(1, (long) 456);
    stmt.setBoolean(2, false);
    stmt.execute();
    ResultSet rs = conn.createStatement().executeQuery(
        "select id, truefalse from booltest");
    while (rs.next()) {
      System.out.println(rs.getLong(1) + " => " + rs.getBoolean(2));
    }
  }
}