Load MYSQL JDBC Driver and run the query : SQL Select Query « Database SQL JDBC « Java






Load MYSQL JDBC Driver and run the query



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class HelloMySQLJDBC {
  Connection connection;

  private void displaySQLErrors(SQLException e) {
    System.out.println("SQLException: " + e.getMessage());
    System.out.println("SQLState:     " + e.getSQLState());
    System.out.println("VendorError:  " + e.getErrorCode());
  }

  public HelloMySQLJDBC() {
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception e) {
      System.err.println("Unable to find and load driver");
      System.exit(1);
    }
  }

  public void connectToDB() {
    try {
      connection = DriverManager.getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");
    } catch (SQLException e) {
      displaySQLErrors(e);
    }
  }

  public void executeSQL() {
    try {
      Statement statement = connection.createStatement();

      ResultSet rs = statement.executeQuery("SELECT * FROM bool");

      while (rs.next()) {
        System.out.println(rs.getString("a") + " " + rs.getBoolean("a"));
        System.out.println(rs.getString("b") + " " + rs.getBoolean("b"));
        System.out.println(rs.getString("c") + " " + rs.getBoolean("c"));
        System.out.println(rs.getString("d") + " " + rs.getBoolean("d"));
      }

      rs.close();
      statement.close();
      connection.close();
    } catch (SQLException e) {
      displaySQLErrors(e);
    }
  }

  public static void main(String[] args) {
    HelloMySQLJDBC hello = new HelloMySQLJDBC();

    hello.connectToDB();
    hello.executeSQL();
  }
}


           
       








Related examples in the same category

1.JDBC select
2.A trivial example of a database query performed with JDBC
3.JDBC Reverse Select
4.Oracle JDBC: select
5.Join two tables