How to Load MySQL JDBC Driver and Run the Query

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - How to Load MySQL JDBC Driver and Run the Query

This Java example program shows how to load MySQL JDBC driver and run the query.

[edit] Java Source Code

  • Package: example.jdbc.sqlselectquery
  • File: HelloMySQLJDBC.java
package example.jdbc.sqlselectquery;
 
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();
    }
}

[edit] What Result You Can Get

Coming soon... Run the program, you will get:

[edit] Required External Libraries and/or Files for this Java Example

In order to run this Java example, one of the following libraries may be required: In order to run this example program, one of the following libraries may be required:


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools