In this blog i will explain how to connect and retrieve data from MySQL database using MySQL JDBC Driver (Connector/J)
We will create a table to hold our contacts
DROP TABLE IF EXISTS `jdbc_test`.`contact`; CREATE TABLE `jdbc_test`.`contact` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(45) default NULL, `phone_number` varchar(45) default NULL, `email_address` varchar(45) default NULL, PRIMARY KEY (`id`) ) ;
Then we will insert a couple of rows
INSERT INTO
contact( name, phone_number, email_address)
VALUES('Mohammad Elkersh', '123456789', 'mohammad@example.com');
INSERT INTO
contact( name, phone_number, email_address)
VALUES('Salem Said', '25798654', 'salem@eexample.com');
The Following is the code to use for connecting to this database and retrieving the contact list
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbModel {
private Statement stmt = null;
private ResultSet rs = null;
public DbModel() {
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/jdbc_test?" +
"user=root&password=");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM contact");
System.out.println(rs);
while (rs.next()) {
String name = rs.getString("name");;
String phone = rs.getString("phone_number");;
String email = rs.getString("email_address");;
System.out.println(" Name: " + name);
System.out.println(" Phone Number: " + phone);
System.out.println("Email Address: " + email);
System.out.println("-------------------------------------");
}
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
public static void main(String[] args) {
new DbModel();
}
}
This code is explain how to use JDBC with MySQL in the simplest form
I hope you found it useful.