Connecting to a MySQL Database with Java (JDBC)

In the beginning of my study time I’ve programmed a MySQL connection in Java for a music collection. After 2 years now I have made a remake of [post id=816]this code[/post] to show how to use the Java Database Connectivity (JDBC). All you need is mysql-connector-java-5.0.8-bin.jar.

I’ve written a small sample for the connection with a WordPress database.

DatabaseController.java

import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class DatabaseController
{
 
  private String host = null;
  private String name = null;
  private String user = null;
  private String password = null;
  static final Logger logger = Logger.getLogger(DatabaseController.class.getName());
 
  public DatabaseController(String host, String name, String user, String password)
  {
    this.host = host;
    this.name = name;
    this.user = user;
    this.password = password;
  }
 
  private Connection getConnection()
  {
    Connection connection = null;
    try
    {
      Class.forName("com.mysql.jdbc.Driver");
      connection = DriverManager.getConnection("jdbc:mysql://" + host + "/" + name + "?zeroDateTimeBehavior=convertToNull", user, password);
    }
    catch (SQLException | ClassNotFoundException ex)
    {
      logger.log(Level.SEVERE, ex.getLocalizedMessage());
    }
    return connection;
  }
 
  public void printWordPressPosts() throws SQLException
  {
    Connection connection = getConnection();
    String query = "SELECT * FROM wp_posts";
    PreparedStatement statement = (PreparedStatement) connection.prepareStatement(query);
    ResultSet result = (ResultSet) statement.executeQuery();    
 
    SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.S" );
 
    while (result.next())
    {
      Date date = result.getDate("post_date");
      String title = result.getString("post_title");
      String content = result.getString("post_content");
 
      if (date != null)
      {
        System.out.println("Posted on: " + dateFormat.format(date) + ", Title: " + title);
      }
    }
  }
}

Execution:

public static void main(String[] args) throws Exception
{
  DatabaseController controller = new DatabaseController("localhost", "database", "db_user", "db_password");
  controller.printWordPressPosts();
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.