Cant get XML parsed data into an SQL database table - java

I have simple XML file (see below)
</Students>`<?xml version="1.0" encoding="utf-8"?>
<Students>
<Student id="1">
<id>001</id>
<firstName>John</firstName>
<lastName>Smith</lastName>
</Student>
<Student id="2">
<id>002</id>
<firstName>Jamie</firstName>
<lastName>Lavery</lastName>
</Student>
<Student id="3">
<id>003</id>
<firstName>Emma</firstName>
<lastName>Lavery</lastName>
</Student>
</Students>
`>
I am trying to parse it into an Arraylist of type student then inserting this into a SQL database table...below is the code for the parser and DB connection
Student.java
package uk.ac.qub.XML_Parser;
public class Student {
private int id;
private String firstName;
private String lastName;
public Student(){
}
public Student(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString() {
return "ID : " + this.id + "\nFirst Name : "
+ this.firstName + "\nLast Name : " + this.lastName;
}
}
XML_Handler.java
package uk.ac.qub.XML_Parser;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XML_Handler extends DefaultHandler {
//List to hold Employees object
private List<Student> studentList = null;
private Student student = null;
//getter method for employee list
public List<Student> getStudentList() {
return studentList;
}
boolean bId = false;
boolean bFirstName = false;
boolean bLastName = false;
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("Student")) {
String id = attributes.getValue("id");
//initialize S object and set id attribute
student = new Student();
student.setId(Integer.parseInt(id));
if (studentList == null)
studentList = new ArrayList<>();
} else if (qName.equalsIgnoreCase("id")) {
//set boolean values for fields, will be used in setting variables
bId = true;
} else if (qName.equalsIgnoreCase("firstName")) {
bFirstName = true;
} else if (qName.equalsIgnoreCase("lastName")) {
bLastName = true;
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("Student")) {
//add Employee object to list
studentList.add(student);
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bId) {
//age element, set age
student.setId(Integer.parseInt(new String(ch, start, length)));
bId = false;
} else if (bFirstName) {
student.setFirstName(new String(ch, start, length));
bFirstName = false;
} else if (bLastName) {
student.setLastName(new String(ch, start, length));
bLastName = false;
}
}
}
XML_SAX_Parser.java
package uk.ac.qub.XML_Parser;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class XML_SAX_Parser {
public void SAX_Parser() {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = saxParserFactory.newSAXParser();
XML_Handler handler = new XML_Handler();
saxParser.parse(new File(
"c:/users/jamie/desktop/DISSERTATION/student.xml"),
handler);
// Get Student list
List<Student> studentList = handler.getStudentList();
for (Student student : studentList)
System.out.println(student);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
DBConnection.java
package uk.ac.qub.DB_Connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import uk.ac.qub.XML_Parser.Student;
public class DBConnection {
// this is a local host url.
private static String url = "jdbc:mysql://localhost/test1";
private static String userName = "root";
private static String password = "";
public void startDB(){
List<Student> studentList = new ArrayList<Student>();
connectionDriver();
passinUpdate(studentList);
}
// Enables java to connect to mysql database
public void connectionDriver() {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connected to mySQL");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void passinUpdate(List<Student> studentList) {
try {
Connection connect2 = DriverManager.getConnection(url, userName,
password);
System.out.println("Established Conenction.....");
String insertStudent = "INSERT INTO Student"
+ "(id, firstName, lastName) VALUES" + "('student.id','student.firstName','student.lastName')";
PreparedStatement statement2 = connect2
.prepareStatement(insertStudent);
statement2.setInt(1, ((Student) studentList).getId());
statement2.setString(2, ((Student) studentList).getFirstName());
statement2.setString(3, ((Student) studentList).getLastName());
statement2.execute();
} catch (SQLException sqlException) {
if (sqlException.getErrorCode() == 1007) {
// Database already exists error
System.out.println(sqlException.getMessage());
} else {
// Some other problems, e.g. Server down, no permission, etc
sqlException.printStackTrace();
}
}
}
}
Output....
Connected to mySQL
Established Conenction.....
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to uk.ac.qub.XML_Parser.Student
at uk.ac.qub.DB_Connection.DBConnection.passinUpdate(DBConnection.java:61)
at uk.ac.qub.DB_Connection.DBConnection.startDB(DBConnection.java:25)
at uk.ac.qub.Start.Start_Program.main(Start_Program.java:9)
This is quite alot of code I know but really not sure where the problem is.....thanks for any help!

Java tells you the exact location of the problem:
uk.ac.qub.DB_Connection.DBConnection.passinUpdate(DBConnection.java:61)
If the argument to the method passinUpdate is
List<Student> studentList
you can not cast this as
(Student) studentList
Do a loop:
for (Student student : studentList) {
statement2.setInt(1, student.getId());
statement2.setString(2, student.getFirstName());
statement2.setString(3, student.getLastName());
statement2.execute();
}

You have a couple of issues in your method
public void passinUpdate(List<Student> studentList) {
try {
Connection connect2 = DriverManager.getConnection("", "",
"");
System.out.println("Established Conenction.....");
//Passing parameters to query
String insertStudent = "INSERT INTO Student" + "(id, firstName, lastName) VALUES" + "(?,?,?)";
//Create a loop for students
for(Student student : studentList){
PreparedStatement statement2 = connect2 .prepareStatement(insertStudent);
//Incorrect cast was used here
statement2.setInt(1, student.getId());
statement2.setString(2, student.getFirstName());
statement2.setString(3, student.getLastName());
statement2.execute();
}
} catch (SQLException sqlException) {
if (sqlException.getErrorCode() == 1007) {
// Database already exists error
System.out.println(sqlException.getMessage());
} else {
// Some other problems, e.g. Server down, no permission, etc
sqlException.printStackTrace();
}
}
}

Related

JdbcSQLSyntaxErrorException: Table "SPORTEVENT" not found; SQL statement, but why?

Im using h2 database for my application, and my task is to create and read queries as practice. The connection works fine, but the table is not found no matter what I try to do. My classes look like the following:
DB connection:
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DatabaseConnectionManager {
private final String url;
private final Properties properties;
public DatabaseConnectionManager(String host, String databaseName, String username,String password){
this.url = "jdbc:h2:mem://"+host+"/"+databaseName;
this.properties = new Properties();
this.properties.setProperty("username",username);
this.properties.setProperty("password",password);
}
public Connection getConnection() throws SQLException{
return DriverManager.getConnection(this.url,this.properties);
}
}
JDBCExecutor:
package database;
import dataaccess.SporteventDAO;
import domain.FootballSportEvent;
import java.sql.*;
import java.time.LocalDateTime;
public class JDBCExecutor {
public static void main(String[] args) {
DatabaseConnectionManager databaseConnectionManager= new DatabaseConnectionManager("localhost","jdbc:h2:mem:sports_betting","sa","");
try{
Connection connection = databaseConnectionManager.getConnection();
SporteventDAO sporteventDAO = new SporteventDAO(connection);
FootballSportEvent footballSportEvent = new FootballSportEvent();
footballSportEvent.setType("FootballSportEvent");
footballSportEvent.setId(2);
Date start = new Date(2022-07-06);
Date end = new Date(2022-07-07);
footballSportEvent.setStart(start);
footballSportEvent.setEnd(end);
footballSportEvent.setResultId(2);
sporteventDAO.create(footballSportEvent);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
SporteventDAO:
package dataaccess;
import domain.FootballSportEvent;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
public class SporteventDAO extends DataAccessObject<FootballSportEvent> {
private static final String INSERT = "INSERT INTO SPORTEVENT (DTYPE, ID, START, END, TITLE, RESULT_ID) VALUES (?,?,?,?,?,?)";
public SporteventDAO(Connection connection){
super(connection);
}
#Override
public FootballSportEvent findById(long id) {
return null;
}
#Override
public List<FootballSportEvent> findAll() {
return null;
}
#Override
public FootballSportEvent update(FootballSportEvent dto) {
return null;
}
#Override
public FootballSportEvent create(FootballSportEvent dto) throws SQLException {
try(PreparedStatement statement = this.connection.prepareStatement(INSERT);){
statement.setString(1,dto.getType());
statement.setInt(2,dto.getId());
statement.setDate(3, (Date) dto.getStart());
statement.setDate(4, (Date) dto.getEnd());
statement.setInt(5, dto.getResultId());
statement.execute();
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
return null;
}
#Override
public void delete(long id) {
}
}
DataTransferObject:
package dataaccess;
public interface DataTransferObject {
int getId();
}
DataAccessObject:
package dataaccess;
import org.h2.jdbc.JdbcConnectionBackwardsCompat;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public abstract class DataAccessObject <T extends DataTransferObject>{
protected final Connection connection;
protected final static String LAST_VAL = "SELECT last_value FROM";
protected final static String CUSTOMER_SEQUENCE = "hp_customer_seq";
public DataAccessObject(Connection connection){
super();
this.connection =connection;
}
public abstract T findById(long id);
public abstract List<T> findAll();
public abstract T update(T dto);
public abstract T create(T dto) throws SQLException;
public abstract void delete(long id);
protected int getLastVal(String sequence){
int key = 0;
String sql = LAST_VAL + sequence;
try(Statement statement = connection.createStatement()) {
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
key = rs.getInt(1);
}
return key;
}catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
FootballSportEventClass:
package domain;
import dataaccess.DataTransferObject;
import java.util.Date;
public class FootballSportEvent implements DataTransferObject
{
private String type;
private String name;
private int id;
private Date end;
private Date start;
private String title;
private int resultId;
public FootballSportEvent(){
}
public FootballSportEvent(String type, String name, int id, Date end, Date start, String title, int resultId) {
this.type = type;
this.name = name;
this.id = id;
this.end = end;
this.start = start;
this.title = title;
this.resultId = resultId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getEnd() {
return end;
}
public void setEnd(Date end) {
this.end = end;
}
public Date getStart() {
return start;
}
public void setStart(Date start) {
this.start = start;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getResultId() {
return resultId;
}
public void setResultId(int resultId) {
this.resultId = resultId;
}
#Override
public String toString() {
return "FootballSportEvent{" +
"type='" + type + '\'' +
", name='" + name + '\'' +
", id=" + id +
", end=" + end +
", start=" + start +
", title='" + title + '\'' +
", resultId=" + resultId +
'}';
}
}
And the following exception it thrown:
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "SPORTEVENT" not found; SQL statement:
INSERT INTO SPORTEVENT (DTYPE, ID, START, END, TITLE, RESULT_ID) VALUES (?,?,?,?,?,?)
Edit:
I also tried using:
this.url = "jdbc:h2:mem://"+host+"/"+databaseName+";DB_CLOSE_DELAY=-1";
but it doesn't work.

IndexOutOfBoundsException when trying to print data called from MySQL database

I'm getting a "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" and I don't even know what is wrong.
I have 4 classes. I get data from two MySQL databases in the first (ConnectionClass) and the second one is a main class from which I run and print the result but for some reason it doesn't work. The third and fourth are normal classes.
The first database is called account which has a few columns and a foreign key(f_id) from the second database f.
My Connection class:
package tryout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class ConnectionClass {
Connection connection;
public void connect() {
String url = "jdbc:mysql://localhost:3306/mydemo";
String username = "root";
String password = "12345";
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<F> getAllFs() {
connect();
ArrayList<F> l = new ArrayList<F>();
String sql="SELECT * FROM f";
try {
Statement s = connection.createStatement();
ResultSet rSet = s.executeQuery(sql);
while(rSet.next()) {
int j=0;
l.get(j).setF_id(rSet.getInt("f_id"));
l.get(j).setF_name(rSet.getString("f_name"));
j++;
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return l;
}
public ArrayList<Account> getAllAccounts() {
connect();
ArrayList<Account> liste = new ArrayList<Account>();
String sql="SELECT * FROM account";
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
int i=0;
liste.get(i).setUsername(rs.getString("username"));
liste.get(i).setPassword(rs.getString("password"));
liste.get(i).setFullname(rs.getString("fullname"));
liste.get(i).setEmail(rs.getString("email"));
liste.get(i).setWebsite(rs.getString("website"));
liste.get(i).setAge(rs.getInt("age"));
liste.get(i).setF((F) rs.getObject("f_id"));
i++;
}
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return liste;
}
}
My main class:
package tryout;
import java.util.ArrayList;
public class MAIN {
public static void main(String[] args) {
ConnectionClass class1 = new ConnectionClass();
ArrayList<Account> list = new ArrayList<Account>();
list = class1.getAllAccounts();
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i).getUsername()+" "+list.get(i).getPassword());
}
}
}
Account.java:
package tryout;
public class Account {
private String username;
private String password;
private String fullname;
private String email;
private String website;
private int age;
private F f;
public Account() {
super();
}
public Account(String username, String password, String fullname, String email, String website, int age, F f) {
super();
this.username = username;
this.password = password;
this.fullname = fullname;
this.email = email;
this.website = website;
this.age = age;
this.f = f;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public F getF() {
return f;
}
public void setF(F f) {
this.f = f;
}
}
F.java:
package tryout;
public class F {
private int f_id;
private String f_name;
public F() {
super();
}
public F(int f_id, String f_name) {
super();
this.f_id = f_id;
this.f_name = f_name;
}
public int getF_id() {
return f_id;
}
public void setF_id(int f_id) {
this.f_id = f_id;
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
}
Here are my databases:
I tried changing getAllAccounts to this:
public ArrayList<Account> getAllAccounts() {
connect();
ArrayList<Account> liste = new ArrayList<Account>();
ArrayList<F> l2 = new ArrayList<F>();
//l2 = getAllFs();
String sql="SELECT * FROM account";
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
Account acc = new Account();
acc.setAge(rs.getInt("age"));
acc.setEmail(rs.getString("email"));
acc.setUsername(rs.getString("username"));
acc.setPassword(rs.getString("password"));
acc.setFullname(rs.getString("fullname"));
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return liste;
}
and when i run it in the main class nothing shows. The error is gone but nothing is printed in the console.
The problem is with the following lines:
ArrayList<F> l = new ArrayList<F>();
String sql="SELECT * FROM f";
try {
Statement s = connection.createStatement();
ResultSet rSet = s.executeQuery(sql);
while(rSet.next()) {
int j=0;
l.get(j).setF_id(rSet.getInt("f_id"));
l.get(j).setF_name(rSet.getString("f_name"));
j++;
}
The list has no element but you are using l.get(j).
In order to understand this problem better, run the following code and you will get Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> l = new ArrayList<String>();
System.out.println(l.get(0));
}
}
Keeping aside the problem, you are initializing j inside while loop which means the incremented value is lost with every iteration. In order to solve the problem, replace
while(rSet.next()) {
int j=0;
l.get(j).setF_id(rSet.getInt("f_id"));
l.get(j).setF_name(rSet.getString("f_name"));
j++;
}
with
while(rSet.next()) {
l.add(rSet.getInt("f_id"));
l.add(rSet.getString("f_name"));
}

How can I make my java code compatible with all the tables in database from which I need to extract the data and then writing it back to Excel file

There is a database (northwind) on my machine and I have to write a code in java so as to extract the data from the table (Customers) stored in the database.
If this was only specific to Customers table then I would have done it but I want to make my code generic so that I can extract data from other tables also by simply giving the name of the table in a string variable.
Please have a look to my code.
Main class
package main;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import model.TableModel;
import service.DBConnection;
import service.WriteExcel;
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
double start = System.nanoTime();
String tableName = "Customers";
Class<?> c = Class.forName(tableName);
Connection conn = new DBConnection().getConnection();
System.out.println("Connection Established");
QueryRunner run = new QueryRunner();
ResultSetHandler<List<TableModel>> resultHandler = new BeanListHandler<TableModel>(c.getClass())
List<TableModel> data = run.query(conn, "SELECT * FROM `" + tableName + "`;",
resultHandler);
WriteExcel we = new WriteExcel(tableName+"_sheet", new File(tableName+".xlsx"));
we.writeMultipleRows(data);
we.writeWorkbookToFile();
System.out.println("File Written Succesfully");
conn.close();
System.out.println("Time Taken: " + (System.nanoTime()-start)/1000000+" ms");
}
}
In the above code, at line 27, If the statement would have been as follows
ResultSetHandler<List<TableModel>> resultHandler = new BeanListHandler<TableModel>(Customers.class);
This is running perfectly, as I said I want this statement to be independent of the table name, making my code more general.
TableModel
package model;
import java.util.List;
public interface TableModel {
public List<String> getObjectAsList();
}
Customers
package model;
import java.util.ArrayList;
import java.util.List;
public class Customers implements TableModel {
private String customerId;
private String companyName;
private String contactName;
private String contactTitle;
private String address;
private String city;
private String region;
private String postalCode;
private String country;
private String phone;
private String fax;
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactTitle() {
return contactTitle;
}
public void setContactTitle(String contactTitle) {
this.contactTitle = contactTitle;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public List<String> getObjectAsList(){
List<String> fields = new ArrayList<>();
fields.add(customerId);
fields.add(companyName);
fields.add(contactName);
fields.add(contactTitle);
fields.add(address);
fields.add(city);
fields.add(region);
fields.add(postalCode);
fields.add(country);
fields.add(phone);
fields.add(fax);
return fields;
}
#Override
public String toString() {
return "{ CustomerID = "+getCustomerId()+","
+ " CompanyName = "+getCompanyName()+","
+ " ContactName = "+getContactName()+","
+ " ContactTitle = "+getContactTitle()+","
+ " Address = "+getAddress()+","
+ " City = "+getCity()+","
+ " Region = "+getRegion()+","
+ " PostalCode = "+getPostalCode()+","
+ " Country = "+getCountry()+","
+ " Phone = "+getPhone()+","
+ " Fax = "+getFax()+"}";
}
}
I have used DbUtils library for extracting database.
Any further suggestion for enhancing my code is welcomed.
If I understand your question right, you could try something like below.
To query the table, you can use run.query(SQL, ResultHandler).
ResultSetHandler<List<Map<String, Object>>> resultHandler = genericResultHandler();
List<Map<String, Object>> result = null;
// Execute the SQL statement and return the results in a List of
// T objects generated by the BeanListHandler.
try
{
result = run.query(sqlQuery, resultHandler, varargs);
}
catch (SQLException e)
{
e.printStackTrace();
}
result.stream().forEach(System.out::println);
The interesting part here is the private method genericResultHandler. For demonstration purposes, I used a HashMap to store the values and the corresponding cloumn names.
private ResultSetHandler<List<Map<String, Object>>> genericResultHandler()
{
return new ResultSetHandler<List<Map<String, Object>>>()
{
#Override
public List<Map<String, Object>> handle(java.sql.ResultSet rs) throws SQLException
{
List<Map<String, Object>> result = new ArrayList<>();
// Query all rows of the table.
while (rs.next())
{
// Get metadata of the table.
java.sql.ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Map<String, Object> data = new HashMap<>();
// For each column store column name and value of the cell into the hashmap.
for (int i = 1; i < cols; i++)
{
String colName = meta.getColumnName(i);
Object value = rs.getObject(colName);
data.put(colName, value);
}
// Add the row to the result list.
result.add(data);
}
return result;
}
};
}
Afterwards some imports I have used:
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
Output would be something like this (for my test table):
{month=JANUARY, temperature=1.6, globalradiation=0.0, monthid=1}
{month=FEBRUARY, temperature=-0.9, globalradiation=0.0, monthid=2}
{month=MARCH, temperature=0.9, globalradiation=0.0, monthid=3}
{month=APRIL, temperature=7.2, globalradiation=0.0, monthid=4}
{month=MAY, temperature=14.1, globalradiation=0.0, monthid=5}

How to get properties of an object stored in ArrayList using Java

I want to print all student objects' properties(name, subject, registrationNo) stored in a ArrayList object.
student details are getting from a database and insert them into student objects.
Then these student objects are insert into the ArrayList.
Finally I want to print these student object properties one by one as follows.
Followings are my codes.
DBconn.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBconn {
static Connection conn;
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/student_database", "root", "");
} catch (SQLException ex) {
}
} catch (ClassNotFoundException ex) {
}
return conn;
}
}
Student.java
public class Student {
private String name;
private String RegistrationNo;
private String course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegistrationNo() {
return RegistrationNo;
}
public void setRegistrationNo(String RegistrationNo) {
this.RegistrationNo = RegistrationNo;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
StudentList.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentList {
public static ArrayList getStudentList() {
ArrayList list = new ArrayList();
String sql = "SELECT * FROM student";
try {
Statement stm = DBconn.getConnection().createStatement();
ResultSet rs = stm.executeQuery(sql);
while (rs.next()) {
Student student = new Student();
student.setName(rs.getString(1));
student.setCourse(rs.getString(2));
student.setRegistrationNo(rs.getString(3));
list.add(student);
}
} catch (SQLException ex) {
}
return list;
}
}
ViewStudent.java
public class ViewStudent {
public static void main(String[] args) {
int size = StudentList.getStudentList().size();
for (int i = 0; i < size; i++) {
System.out.println(StudentList.getStudentList().get(i));
//I want to get all student's name,subject and registrationNo
}
}
}
Thanks.
Simply give Student a public String toString() method override, one that returns a String holding all key properties, and then this will work fine:
System.out.println(StudentList.getStudentList().get(i));
Instead of System.out.println(StudentList.getStudentList().get(i));, you should access the student's properties and print it out.
Student s = (Student) StudentList.getStudentList().get(i);
System.out.println(s.getName());
System.out.println(s.getCourse());
System.out.println(s.getRegistrationNo());

When I am entering search, the results are not displayed

LabServiceManagement.Java
package com.bean;
public class LabServiceManagement {
private String lspName;
private String address;
private int zipcode;
private String state;
private String city;
private String testName;
private int testCode;
private String testDescription;
private double costOfTest;
private String lab_home;
public String getLspName() {
return lspName;
}
public void setLspName(String lspName) {
this.lspName = lspName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTestName() {
return testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public int getTestCode() {
return testCode;
}
public void setTestCode(int testCode) {
this.testCode = testCode;
}
public String getTestDescription() {
return testDescription;
}
public void setTestDescription(String testDescription) {
this.testDescription = testDescription;
}
public double getCostOfTest() {
return costOfTest;
}
public void setCostOfTest(double costOfTest) {
this.costOfTest = costOfTest;
}
public String getLab_home() {
return lab_home;
}
public void setLab_home(String lab_home) {
this.lab_home = lab_home;
}
}
DBUtility.java
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtility {
static final String driver = "oracle.jdbc.driver.OracleDriver";
static final String dbURL = "jdbc:oracle:thin:#172.26.132.40:1521:ORCLILP";
static final String dbUserName = "aja16core";
static final String dbPassword = "aja16core";
public static Connection getConnection()
{
Connection con=null;
try {
// load the JDBC-ODBC Bridge driver
Class.forName(driver);
// connect to db using DriverManager
con = DriverManager.getConnection(dbURL, dbUserName, dbPassword);
}
catch (ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}
return con;
}
public static void closeResultSet(ResultSet rs) {
if(rs!= null)
{
try
{
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
public static void closeStatement(PreparedStatement ps) {
if(ps!= null)
{
try
{
ps.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
public static void closeConnection(Connection con) {
if(con!= null)
{
try
{
con.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
LabServiceDAO.java
package com.dao;
import com.bean.LabServiceManagement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class LabServiceDAO {
public ArrayList<LabServiceManagement> searchcity(String city)
{
ArrayList<LabServiceManagement> result_list= new ArrayList<LabServiceManagement>();
Connection con=DBUtility.getConnection();
PreparedStatement ps=null;
ResultSet rs=null;
try
{
ps=con.prepareStatement("select * from LSP where CITY=? ");
ps.setString(1, city);
rs=ps.executeQuery();
while(rs.next())
{
String lspName=rs.getString("lspName");
String address=rs.getString("address");
int zipcode=rs.getInt("zipcode");
String state=rs.getString("state");
String testName=rs.getString("testName");
int testCode=rs.getInt("testCode");
String testDescription =rs.getString("testDescription");
double costOfTest=rs.getDouble("costOfTest");
String lab_home=rs.getString("lab_home");
LabServiceManagement l=new LabServiceManagement();
l.setLspName(lspName);
l.setAddress(address);
l.setZipcode(zipcode);
l.setState(state);
l.setCity(city);
l.setTestName(testName);
l.setTestCode(testCode);
l.setTestDescription(testDescription);
l.setCostOfTest(costOfTest);
l.setLab_home(lab_home);
result_list.add(l);
}
} catch (SQLException e)
{
e.printStackTrace();
}
finally
{
DBUtility.closeResultSet(rs);
DBUtility.closeStatement(ps);
DBUtility.closeConnection(con);
}
return result_list;
}
}
LabService.java
package com.service;
import java.util.ArrayList;
import com.bean.LabServiceManagement;
import com.dao.LabServiceDAO;
public class LabService {
public ArrayList<LabServiceManagement> searchcity(String city)
{
LabServiceDAO searchdao = new LabServiceDAO();
ArrayList<LabServiceManagement> result_list= searchdao.searchcity(city);
return result_list;
}
}
I have created table in SQL
I inserted few data
I coded for search city only, where I given mumbai which is already there in database, but result set is not coming
Can you please find the mistake, where I am gone wrong?

Categories