Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

***JAVA*** I can connect my Java program to mySQL databse, I just can\'t figure

ID: 3719066 • Letter: #

Question

***JAVA***

I can connect my Java program to mySQL databse, I just can't figure out how to retrieve the data and store it?

How do I take the information from the following MySQL Tabel:

DROP DATABASE IF EXISTS mma;

CREATE DATABASE mma;

USE mma;

CREATE TABLE Customer_List(

Email VARCHAR(100),

FirstName VARCHAR(50),

LastName VARCHAR(50),

PRIMARY KEY (Email));

INSERT INTO Customer_List (Email, FirstName, LastName) VALUES

('frankjones@yahoo.com','Frank','Jones'),

('johnsmith@hotmail.com','John','Smith'),

('seagreen@levi.com','Cynthia','Green'),

('wendyk@warners.com','Wendy','Kowolski');

GRANT SELECT, INSERT, DELETE, UPDATE

ON mma.*

TO mma_user@localhost

IDENTIFIED BY 'sesame';

SELECT * FROM Customer_List;

and create a Customer object:

public class Customer {

int Id;
String Email;
String FirstName;
String LastName;
private static int counter = 0;

public Customer() {

String Email = "";
String FirstName = "";
String LastName = "";
}

public Customer(String fName, String lName, String email) {

Id = ++counter;
this.FirstName = fName;
this.LastName = lName;
this.Email = email;
}
}

to be stored in an ArrayList <Customer> newCustomer = new ArrayList<>();

Explanation / Answer

//Note : To connect java application with the mysql database mysqlconnector.jar file is required to be loaded.

//MainClass.java

import java.sql.*;  

class MainClass{  

public static void main(String args[]){  

// size of ArrayList

int n = 5;

ArrayList <Customer> newCustomer = new ArrayList<Customer>(n);

try{  

Class.forName("com.mysql.jdbc.Driver");  

Connection con=DriverManager.getConnection(  

"jdbc:mysql://localhost:3306/mma","db_username","db_password");  

//here mma is database name, db_username is username and password  

Statement stmt=con.createStatement();  

ResultSet rs=stmt.executeQuery("select * from Customer_List");  

while(rs.next())  

{

Customer C =new Customer(rs.getString(1),rs.getString(2),rs.getString(3));

newCustomer.add(C);

//System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));  

}

con.close();  

}catch(Exception e){ System.out.println(e);}  

}  

}  

class Customer {

int Id;
String Email;
String FirstName;
String LastName;
private static int counter = 0;

public Customer() {

String Email = "";
String FirstName = "";
String LastName = "";
}

public Customer(String fName, String lName, String email) {

Id = ++counter;
this.FirstName = fName;
this.LastName = lName;
this.Email = email;
}
}