Java MySQL null resultset - java

I'm trying to write a small java application that returns the details for an employee. Here's my Employee class.
public class Employees {
private int id;
private Date dateofBirth;
private String firstName;
private String lastName;
private enum gender{
M, F;
}
private gender employeeGender;
private Date dateHired;
public String getEmployeeGender() {
return this.employeeGender.name();
}
public void setEmployeeGender(String employeeGender) {
this.employeeGender = gender.valueOf(employeeGender);
}
/*Getters, setters omitted*/
Here's my DAO class
public class EmployeeDao {
final String TABLE_EMPLOYEES = "employees";
final String COLUMN_EMPLOYEES_ID = "emp_no";
final String COLUMN_EMPLOYEES_DOB = "birth_date";
final String COLUMN_EMPLOYEES_FIRST_NAME = "first_name";
final String COLUMN_EMPLOYEES_LAST_NAME = "last_name";
final String COLUMN_EMPLOYEES_GENDER = "gender";
final String COLUMN_EMPLOYEES_HIRE_DATE = "hire_date";
final String QUERY_EMPLOYEES = "SELECT * FROM " + TABLE_EMPLOYEES + " WHERE " + COLUMN_EMPLOYEES_ID + " = ?";
public Employees getEmployeeDetails(int employeeId) {
Employees employee = new Employees();
try (DbConnection dbConnection = new DbConnection();
Connection databaseConnection = dbConnection.getConn();
PreparedStatement selectFromEmployees = databaseConnection.prepareStatement(QUERY_EMPLOYEES)) {
selectFromEmployees.setInt(1, employeeId);
try (ResultSet result = selectFromEmployees.executeQuery()) {
if (result.next() == false) {
System.out.println("Empty Resultset");
}
while (result.next()) {
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return employee;
}
}
But when I try to run the app in main method like this, I get an output with null values.
public static void main(String[] args) {
EmployeeDao employeeDao = new EmployeeDao();
Employees employees = employeeDao.getEmployeeDetails(39256);
System.out.println(employees.getId() + " \n" + employees.getFirstName() + " \n" + employees.getLastName() + " \n" + employees.getDateofBirth() + " \n" + employees.getDateHired());
}
This is the output.
This is how the corresponding row looks like in the database

You should not call next twice, since it will move the cursor forward again. Try this:
if (result.next() == false) {
System.out.println("Empty Resultset");
} else {
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}

Calling ResultSet#next moves the cursor forward a row, so your if condition loses the first row. Since you know your query can return at most one row, you don't need the while loop at all, however:
public Employees getEmployeeDetails(int employeeId) throws SQLException {
Employees employee = null;
try (DbConnection dbConnection = new DbConnection();
Connection databaseConnection = dbConnection.getConn();
PreparedStatement selectFromEmployees =
databaseConnection.prepareStatement(QUERY_EMPLOYEES)) {
selectFromEmployees.setInt(1, employeeId);
try (ResultSet result = selectFromEmployees.executeQuery()) {
if (result.next()) {
employee = new Employees();
employee.setId(result.getInt(COLUMN_EMPLOYEES_ID));
employee.setFirstName(result.getString(COLUMN_EMPLOYEES_FIRST_NAME));
employee.setLastName(result.getString(COLUMN_EMPLOYEES_LAST_NAME));
employee.setDateofBirth(result.getDate(COLUMN_EMPLOYEES_DOB));
employee.setEmployeeGender(result.getString(COLUMN_EMPLOYEES_GENDER));
employee.setDateHired(result.getDate(COLUMN_EMPLOYEES_HIRE_DATE));
}
}
}
return employee;
}

No need to add extra result.next() comparison.
if (result.next() == false) {
System.out.println("Empty Resultset");
}
while (result.next()){
}
while will execute only if there are any rows.
Check the size of list generated before using to check if it contains value or not.

Related

SQLite truncates my data

I have data that looks like this in console:
"to add:
rand_num = 1-231881-6-70885-12
name = heat boy
type = caucasian
price = 700.0
date = 2018-08-01"
Instead I get this for some reason in database:
"to add:
rand_num = 1-231881-6-70885-12
name = heat boy
type = caucasian
price = 70"
My controller:
public class Controller {
private description = "to add: \n"+
"rand_num = 1-231881-6-70885-12 \n"+
"name = heat boy \n"+
"type = caucasian \n"+
"price = 700.0 \n"+
"date = 2018-08-01"
private Model textFields() {
Model model = new Model();
model.setRand_num(description.getText());
}
try {
DAOClass daoClass = new DAOCLass();
daoClass.insert(textFields());
}
catch(SQLException e){
System.out.println(e);
}catch(ClassNotFoundException e) {
System.out.println(e);
}
}
My model:
public class model {
private SimpleStringProperty description;
public Model() {
this("");
}
public model(String description) {
super();
this.rand_num = new SimpleStringProperty(description);
}
//getter
public String getDescription() {
return description.get();
}
//setter
public void setDescription(String description) {
this.description.set(description);
}
//property
public StringProperty descriptionProperty(){
return description;
}
#Override
public String toString() {
return "to add: " +
}
}
DAO class
public class DAO {
public void insert(Model model) throws SQLException, ClassNotFoundException {
//initializing PreparedStatement
PreparedStatement preparedStatement = null;
String updateQuery =
"INSERT INTO modelDB \n" +
"(description) \n" +
"VALUES \n" +
"(?)";
//Execute DELETE operation
try {
preparedStatement = connection.prepareStatement(updateQuery);
preparedStatement.setString(1, model.description());
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.out.print("Error: " + e);
throw e;
}
finally {
if(preparedStatement != null)
{
preparedStatement.close();
}
}
}
}
My SQLite table structure:
CREATE TABLE userActivityLogs (
logId INTEGER PRIMARY KEY AUTOINCREMENT,
description VARCHAR (10000)
);
Now I know there is no limit for SQLite and even if there was I am using varChar(10000). It all displays perfectly on console but once it is in the database it is truncated. Why is that and how can I fix this issue?
I dont´t see your random number truncated so the varchar(10000) isn´t at play here.
What i see in your code is:
preparedStatement.setString(4, model.getPrice());
preparedStatement.setString(4, model.getDate());
You are using the same index for Price and Date.

JAVA linking ID to name from other table

I got a tableview with a tablecolumn ("ID").
How can i link the ID to show the value?
For example: ID 90 has to be "Shop" and ID 91 has to be "Wallmart"..
I'm using 2 tables:
Person(id, personName, personShopID)
Items(id, shopName)
PersonShopID links to ITEMS id and i have to show the shopName instead of the ID..
Note: I'm using JavaFX and i'm getting data from mysql database and i'm using tcShopName.setCellValueFactory(new PropertyValueFactory<>("personShopID"));
kind regards !
package databag;
import java.sql.Timestamp;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import vivesgoal.controller.CustomDate;
/**
*
* #author Lowie Menu
*/
public class PersoonBag {
private int id;
private String naam;
private String voornaam;
private Date geboortedatum;
private String opmerking;
private boolean isTrainer;
private int ploeg_id;
public PersoonBag(int id, String naam, String voornaam, Date geboortedatum, String opmerking,boolean isTrainer, int ploeg_id){
this.id=id;
this.naam=naam;
this.voornaam=voornaam;
this.geboortedatum=geboortedatum;
this.opmerking=opmerking;
this.isTrainer=isTrainer;
this.ploeg_id=ploeg_id;
}
public PersoonBag()
{
}
public int getId() {
return id;
}
public String getNaam() {
return naam;
}
public String getVoornaam() {
return voornaam;
}
public Date getGeboortedatum() {
return geboortedatum;
}
public String getGeboortedatumAlter(){
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String datum = df.format(geboortedatum);
return datum;
}
public CustomDate getMyDate(){
return new CustomDate(geboortedatum.getTime());
}
public java.util.Date getGeboortedatumUtil(){
return geboortedatum;
}
public String getOpmerking() {
return opmerking;
}
public boolean isIsTrainer() {
return isTrainer;
}
public int getPloeg_id() {
return ploeg_id;
}
public void setId(int id) {
this.id = id;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setVoornaam(String voornaam) {
this.voornaam = voornaam;
}
public void setGeboortedatum(Date geboortedatum) {
this.geboortedatum =geboortedatum;
}
public void setOpmerking(String opmerking) {
this.opmerking = opmerking;
}
public void setIsTrainer(boolean isTrainer) {
this.isTrainer = isTrainer;
}
public void setPloeg_id(int ploeg_id) {
this.ploeg_id = ploeg_id;
}
}
and class Team (dutch ploeg)
package databag;
/**
*
* #author Lowie Menu
*/
public class PloegBag {
private int id;
private String naam;
private String niveau;
private int trainer_id;
public PloegBag(int id, String naam, String niveau, int trainer_id){
this.id = id;
this.naam = naam;
this.niveau = niveau;
this.trainer_id = trainer_id;
}
public PloegBag(){
}
public void setId(int id) {
this.id = id;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setNiveau(String niveau) {
this.niveau = niveau;
}
public void setTrainer_id(int trainer_id){
this.trainer_id=trainer_id;
}
public int getId() {
return id;
}
public String getNaam() {
return naam;
}
public String getNiveau() {
return niveau;
}
public int getTrainer_id(){
return trainer_id;
}
}
Note: i'm trying to link ploeg_id from PersoonBag to the name of PloegBag(ploegnaam).
This sql code gets me the name of the club matching the id
select * from persoon AS p INNER JOIN ploeg AS ploeg ON p.ploeg_id =ploeg.id where ploeg.naam=?"
Update: no value in ploeg.naam? maybe issue here
p
ublic ArrayList<PersoonBag> zoekAlleSpelers() throws DBException, ApplicationException {
ArrayList<PersoonBag> pb = new ArrayList<>();
try (Connection conn = ConnectionManager.getConnection();) {
try(PreparedStatement stmt = conn.prepareStatement(
"select * from persoon inner join ploeg where persoon.ploeg_id = ploeg.id");) {
// execute voert elke sql-statement uit, executeQuery enkel de eenvoudige
stmt.execute();
// result opvragen (en automatisch sluiten)
try (ResultSet rs = stmt.getResultSet()) {
// van alle rekennigen uit de database,
// RekeningBag-objecten maken en in een RekeningVector steken
while (rs.next()) {
PersoonBag p = new PersoonBag();
PloegBag ploeg = new PloegBag();
// ploeg.setId(rs.getInt("id"));
ploeg.setNaam(rs.getString("naam"));
p.setId(rs.getInt("id"));
p.setNaam(rs.getString("naam"));
p.setVoornaam(rs.getString("voornaam"));
p.setGeboortedatum(rs.getDate("geboortedatum"));
p.setOpmerking(rs.getString("opmerking"));
p.setIsTrainer(rs.getBoolean("isTrainer"));
p.setPloeg_id(ploeg);
pb.add(p);
}
return pb;
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - resultset");
}
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - statement");
}
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - connection");
}
}
Still have'nt found the issue.. this is function to store the data from the sql query in the table note: this works only ploegname isn't showing
PersoonDB pdb = new PersoonDB();
ArrayList<PersoonBag> persoonbag = new ArrayList<>();
try {
ArrayList<PersoonBag> spelersLijst = pdb.zoekAlleSpelers();
for (PersoonBag r : spelersLijst) {
PersoonBag speler = new PersoonBag(r.getId(),r.getNaam(), r.getVoornaam(),r.getMyDate(),r.getOpmerking(), r.isIsTrainer(),r.getPloeg_id());
persoonbag.add(speler);
}
ObservableList<PersoonBag> spelers = FXCollections.observableArrayList(persoonbag);
taSpelers.setItems(spelers);
Cell items:
#FXML
private TableView<PersoonBag> taSpelers;
#FXML
private TableColumn tcFamilienaam;
#FXML
private TableColumn tcVoornaam;
#FXML
private TableColumn tcOpmerking;
#FXML
private TableColumn<PersoonBag, CustomDate> tcGeboortedatum;
#FXML
private TableColumn<PersoonBag, PloegBag> tcPloeg;
#Override
public void initialize(URL url, ResourceBundle rb) {
tcFamilienaam.setCellValueFactory(new PropertyValueFactory<>("naam"));
tcVoornaam.setCellValueFactory(new PropertyValueFactory<>("voornaam"));
tcGeboortedatum.setCellValueFactory(new PropertyValueFactory<PersoonBag, CustomDate>("geboortedatum"));
tcOpmerking.setCellValueFactory(new PropertyValueFactory<>("opmerking"));
tcPloeg.setCellValueFactory(new PropertyValueFactory<>("ploeg"));
tcPloeg.setCellFactory(tc -> new TableCell<PersoonBag, PloegBag>() {
#Override
public void updateItem(PloegBag ploeg, boolean empty) {
if (empty || ploeg ==null){
setText("");
} else{
setText(ploeg.getNaam());
}
}
});
UPDATE!!! i'm almost there! It's getting the 'naam' data from persoon instead of 'naam' from ploeg!
issue:
while (rs.next()) {
PloegBag ploeg = new PloegBag();
ploeg.setId(rs.getInt("id"));
ploeg.setNaam(rs.getString("naam"));
PersoonBag p = new PersoonBag();
p.setId(rs.getInt("id"));
p.setNaam(rs.getString("naam"));
p.setVoornaam(rs.getString("voornaam"));
p.setGeboortedatum(rs.getDate("geboortedatum"));
p.setOpmerking(rs.getString("opmerking"));
p.setIsTrainer(rs.getBoolean("isTrainer"));
p.setPloeg(ploeg);
pb.add(p);
}
when i'm putting niveau instead of 'naam' it's get me the correct matching result! now i need the name..!
Instead of storing the id of the linked item, store a reference to the item itself. So your PersoonBag class will look like:
public class PersoonBag {
private int id;
private String naam;
private String voornaam;
private Date geboortedatum;
private String opmerking;
private boolean isTrainer;
private PloegBag ploeg;
public PersoonBag(int id, String naam, String voornaam, Date geboortedatum, String opmerking,boolean isTrainer, PloegBag ploeg){
this.id=id;
this.naam=naam;
this.voornaam=voornaam;
this.geboortedatum=geboortedatum;
this.opmerking=opmerking;
this.isTrainer=isTrainer;
this.ploeg=ploeg;
}
public PersoonBag()
{
}
public PloegBag getPloeg() {
return ploeg ;
}
public void setPloeg(PloegBag ploeg) {
this.ploeg = ploeg ;
}
// other get/set methods ...
}
Now you can load everything at once using an inner join in the SQL:
String sql = "select * from persoon inner join ploeg where persoon.ploeg_id = ploeg.id";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
List<Persoon> persoonList = new ArrayList<>();
while (rs.next()) {
PloegBag ploeg = new PloegBag();
// populate ploeg with data from rs...
PersoonBag persoon = new PersoonBag();
persoon.setPloeg(ploeg);
// populate persoon with remaining data from rs...
persoonList.add(persoon);
}
(Obviously you can modify the SQL code, e.g. to retrieve specific items from the database, or just generally to improve it, etc.)
Now your JavaFX code looks like:
TableView<PersoonBag> persoonTable = new TableView<>();
TableColumn<PersoonBag, PloegBag> tcPloeg = new TableColumn<>("Ploeg");
tcPloeg.setCellValueFactory(new PropertyValueFactory<>("ploeg"));
// other columns...
To get the cells to display the value you need from the PloegBag, there are two ways. The "quick and dirty" way is just to define a toString() method in the PloegBag class:
public class PloegBag {
// ...
#Override
public String toString() {
return naam ;
}
}
This isn't very satisfactory, though, as you might want to toString() method to do something else for other reasons in your application. The "proper" way is to use a cell factory:
tcPloeg.setCellFactory(tc -> new TableCell<PersoonBag, PloegBag>() {
#Override
public void updateItem(PloegBag ploeg, boolean empty) {
if (empty || ploeg == null) {
setText(null);
} else {
setText(ploeg.getNaam());
}
}
});
1) establish a Connection to your database from your Java-program by using JDBC:
private static Connection getDBConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?autoReconnect=true&user=myUser&password=myPass");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error on getDBCOnnection "+e.toString());
}
return connection;
}
2) Query your Items table in a query like this:
SELECT shopName FROM Items WHERE ID = 90
Java:
public static ResultSet runQuery(String query) {
if(conn == null){
conn = getDBConnection();
}
Statement stmt;
ResultSet rs;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
return rs;
} catch (SQLException e) {
System.out.println(e + " " + e.getMessage());
return null;
}
}
3) Read the result
ResultSet rs = runQuery(query);
String result = rs.getString(1);
Hibernate could do it all for you, including queries... just saying... Although steep learning curve if doing it for the first time... You need to model your container object to have these fields, for example person would have:
class Person{
long id;
String name;
String shopName;
...
}
Then in your data service (provider of data) you would query for that, lets say:
SELECT p.id, p.name, s.name
FROM person p, shop s
WHERE p.shopId = s.shopId;
and provide simple rowmapper
#Ovrride
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person(rs.getInt("personId"), rs.getString("personName"), rs.getString("shopName"));
return person;
}
You end up with list of Persons, which you can operate on within app. As someone mentioned earlier, you would want to do this, beforehand. Every time you need that list you would hit a local cache, instead of going back to DB. You could set a policy to refresh cache if needed.

I need the method to return all values from the select query

My project requires me to retrieve data from a mySQL database. The method is contained in a class that contains dozens of other database access methods for my java program. The plan is to call this methods from any other class that requires the data from the database. The problem is in java you can only return one data type and yet I need to get back all data from the tuple obtained.
What is the best way to get my method to return (in another class that calls this method) all the data from my query?
Here's the code snippet:
// SELECT QUERIES
public void select_H_Customer_Table(int get_intCustomerID) {
int intCustomerID = get_intCustomerID;
sql = "SELECT intCustomerID, vachCustomerTitle, vachCustomerFirstName, vachCustomerSurnames, dteCustomerDOB, vachCustomerAddressStreet, vachCustomerAddressTown, vachCustomerAddressCounty, vachCustomerAddressPostalCode, intCustomerHomePhone, intCustomerWorkPhone, intCustomerMobilePhone, vachCustomerEmail FROM h_customers " + "WHERE" + " intCustomerID=?";
try {
st.setInt(1, intCustomerID);
rs = st.executeQuery();
while (rs.next()){
int rs_intCustomerID = rs.getInt("intCustomerID");
String rs_vachCustomerTitle = rs.getString("vachCustomerTitle");
String rs_vachCustomerFirstName = rs.getString("vachCustomerFirstName");
String rs_vachCustomerSurnames = rs.getString("vachCustomerSurnames");
String rs_dteCustomerDOB = rs.getString("dteCustomerDOB");
String rs_vachCustomerAddressStreet = rs.getString("vachCustomerAddressStreet");
String rs_vachCustomerAddressTown = rs.getString("vachCustomerAddressTown");
String rs_vachCustomerAddressCounty = rs.getString("vachCustomerAddressCounty");
String rs_vachCustomerAddressPostalCode = rs.getString("vachCustomerAddressPostalCode");
int rs_intCustomerHomePhone = rs.getInt("intCustomerHomePhone");
int rs_intCustomerWorkPhone = rs.getInt("intCustomerWorkPhone");
int rs_intCustomerMobilePhone = rs.getInt("intCustomerMobilePhone");
String rs_txtCustomerEmail = rs.getString("txtCustomerEmail");
}
} catch (SQLException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
}
You have to create a Customer class and the query method have to return a Customer
The object Customer should be like:
class Customer {
public Customer() {};
private int iD;
private String title;
private String firstName;
private String surnames;
private String dOB;
private String addressStreet;
private String addressTown;
private String addressCounty;
private String addressPostalCode;
private int homePhone;
private int workPhone;
private int mobilePhone;
private String customerEmail;
// Generate getters and setters
}
And the query method should be:
public Customer getCustomerById(int customerID) {
String sql = "SELECT intCustomerID, vachCustomerTitle, vachCustomerFirstName, vachCustomerSurnames, dteCustomerDOB, vachCustomerAddressStreet, vachCustomerAddressTown, vachCustomerAddressCounty, vachCustomerAddressPostalCode, intCustomerHomePhone, intCustomerWorkPhone, intCustomerMobilePhone, vachCustomerEmail FROM h_customers " + "WHERE" + " intCustomerID=?";
try {
st.setInt(1, customerID);
rs = st.executeQuery();
while (rs.next()){
Customer customer = new Customer();
customer.setId(rs.getInt("intCustomerID"));
customer.setTitle(rs.getString("vachCustomerTitle"));
customer.setFirstName(rs.getString("vachCustomerFirstName"));
//...
return customer;
}
} catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
return null;
} finally {
if(rs != null) {
rs.close();
}
}
}
Create a pojo (an entity class) and use select * query. Once you have the resultset create the object of pojo and populate the fields and return
public class MyData{
private String name;
private String desc;
//constructor or setter getter
}
And once you have the resultset create new MyData() with the fields
MyData data = null;
while(resultSet.next()){
data = new MyData(resultSet.getString("NAME"), resultSet.getString("DESC"));
}
return data;
Something like this !!!
If you have a lot of fields, I would prefer setters and getters instead of the parameterized constructor

Trouble setting a variable with class scope from the constructor - Java, MySQL

I'm trying to set a variable with class scope with a constructor, whenever I print out from within the constructor the variable is set to the correct value but whenever I try to use that variable in another method within the same class the value is null. How do I use the firstNameTest variable outside of the constructor correctly?
This is the constructor and calling method:
public class Member extends javax.swing.JFrame {
DefaultTableModel rentalsTableModel;
String customerID;
String firstNameTest; //Variable declared with class scope.
public Member() {
initComponents();
rentalsTableModel = (DefaultTableModel)tblRentals.getModel();
}
Member(String firstName, String lastName, String phoneNumber, String email, String over18, String dateJoined, String dateExpired, String fines) throws SQLException {
System.out.println(firstName); // Successfully prints value.
firstNameTest = firstName;
System.out.println(firstNameTest); // Successfully prints value.
}
...
private void btnChangeCustomerActionPerformed(java.awt.event.ActionEvent evt) {
customerID = JOptionPane.showInputDialog(null, "Enter Customer ID.");
MemberDAO member = new MemberDAO();
try {
List membersDetails = member.getMembersDetails(customerID);
System.out.println(firstNameTest); // Value is null.
txtFullName.setText(firstNameTest);
} catch (SQLException ex) {
System.err.println(ex);
System.out.println("Failed to get Details.");
JOptionPane.showMessageDialog(null, "Failed to retrieve data.");
}
}
Called Method:
public List<Member> getMembersDetails(String ID) throws SQLException{
List<Member> membersDetails = new ArrayList();
String getMembershipDetails = "SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM members"
+ " WHERE member_id = " + ID + ";";
try {
DBConnection mc = new DBConnection();
dbConnection = mc.getConnection();
statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(getMembershipDetails);
while(rs.next()){
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String phoneNumber = rs.getString("phone_number");
String email = rs.getString("email");
String over18 = rs.getString("over_18");
String dateJoined = rs.getString("date_joined");
String dateExpired = rs.getString("date_expire");
String fines = rs.getString("fines");
System.out.println(firstName);
System.out.println(dateExpired);
Member m;
m = new Member(firstName, lastName, phoneNumber, email, over18, dateJoined, dateExpired, fines);
membersDetails.add(m);
System.out.println(membersDetails.get(0));
}
} catch (SQLException ex){
System.err.println(ex);
System.out.println("Failed to get Membership Details.");
return null;
} finally{
if (ps != null){
ps.close();
}
if (dbConnection != null){
dbConnection.close();
}
} return membersDetails;
}
Change this line -
System.out.println(firstNameTest); // Value is null.
to
System.out.println(((Member)membersDetails.get(0)).firstNameTest); // Value is null.

Iterating through an array populated from a MySQL table

There's a fair bit of code involved and I'm not sure how much detail to go into, but I'm populating a treemap with data from a mysql table and I'm having trouble iterating through it.
Here's the code for the class containing the treemap
public class SeasonResults{
private static Map<String,SeasonResults> allResults = new TreeMap<String,SeasonResults>();
private String hometeam;
private String awayteam;
private String result;
private static SeasonResults result6;
public static SeasonResults add(String hometeam, String awayteam, String result)
{
result6 = new SeasonResults(hometeam, awayteam, result);
allResults.put(hometeam,result6);
return result6;
}
private SeasonResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;
}
public static Collection<SeasonResults> getCollection()
{
return allResults.values();
}
#Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}
And here's the code where I populate the array and then try and iterate through it.
public void HeadToHead(){
try
{
//Sets up the connedtion to the database and installs drivers which are required.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");
String SQL = "SELECT * FROM PreviousSeasons WHERE HomeTeam=? and AwayTeam=?";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
prepst.setString(2,box2.getSelectedItem().toString());
rs = prepst.executeQuery();
while (rs.next())
{
//This retrieves each row of League table and adds it to an array in the League Results class.
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
custs = (hometeam + "," + awayteam + "," + result); // Takes all the variables containging a single customers information and puts it into a string, seperated by commas.
SeasonResults.add(hometeam, awayteam, result);
}
}
catch (Exception e)
{
System.out.println("Error " +e);
}
Seasonrecord = SeasonResults.getCollection();
seasons = new SeasonResults[Seasonrecord.size()];
Iterator iterateSeason = Seasonrecord.iterator();
int i = 0;
while(iterateSeason.hasNext()){
seasons[i] = (SeasonResults)iterateSeason.next();
i++;
if(result.equals("HW")){
hometeamvalue = hometeamvalue + 50;
}
else if(result.equals("D")){
hometeamvalue = hometeamvalue + 10;
awayteamvalue = awayteamvalue + 10;
}
else{
if(result.equals("AW")){
awayteamvalue = awayteamvalue + 50;
}
}
}
}
There are 5 'result' fields in the database. 2 are 'HW', 2 are 'AW', and 1 is 'D'. What I'm trying to do is print out 'hometeamvalue' and 'awayteamvalue' but when I do the value is printed as only 10. Only the first field's value is used.
I use the same code to iterate through the array when I want to display the results in a GUI, and all the fields are shown. But when I try and do some calculations with them, it doesn't work.
Any ideas what the problem is?
You have to do like this
SeasonResults.java
public class SeasonResults{
private String hometeam;
private String awayteam;
private String result;
public String getHometeam() {
return hometeam;
}
public void setHometeam(String hometeam) {
this.hometeam = hometeam;
}
public String getAwayteam() {
return awayteam;
}
public void setAwayteam(String awayteam) {
this.awayteam = awayteam;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public SeasonResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;
}
#Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}
HeadToHaed method
public void HeadToHead(){
String hometeam,awayteam,result;
int hometeamvalue,awayteamvalue;
List<SeasonResults> allResults = new ArrayList<SeasonResults>();
try
{
//Sets up the connedtion to the database and installs drivers which are required.
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");
String SQL = "SELECT * FROM PreviousSeasons WHERE HomeTeam=? and AwayTeam=?";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
prepst.setString(2,box2.getSelectedItem().toString());
ResultSet rs = prepst.executeQuery();
SeasonResults seasonResults=null;
while (rs.next())
{
//This retrieves each row of League table and adds it to an array in the League Results class.
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
seasonResults=new SeasonResults( hometeam, awayteam, result) ;
custs = (hometeam + "," + awayteam + "," + result); // Takes all the variables containging a single customers information and puts it into a string, seperated by commas.
allResults.add(seasonResults);
}
}
catch (Exception e)
{
System.out.println("Error " +e);
}
System.out.println("SIze of ArrayList::"+allResults.size());
for(SeasonResults temp:allResults)
{
if(temp.getResult().equals("HW")){
hometeamvalue = hometeamvalue + 50;
}
else if(temp.getResult().equals("D")){
hometeamvalue = hometeamvalue + 10;
awayteamvalue = awayteamvalue + 10;
}
else{
if(temp.getResult().equals("AW")){
awayteamvalue = awayteamvalue + 50;
}
}
}
}
Let Me Know If U Face Any Issues

Categories