OutOfMemoryError - java

I'm making a Timetable scheduler as a final year project. For the last two days, I'm getting an OutOfMemoryException. I have read a lot about the exception, and tried to increase the memory alloted through the -Xms and -Xmx options. None of these seem to work for me.
I profiled the project, and found that the maximum space was consumed by hashmap objects, and also by the MySQL connection. I have used a static connection as follows
public final class Connector
{
private static Connector connector;
Connection con;
String driverName;
String dbname;
String username;
String password;
String connString;
private Connector(){
driverName = "com.mysql.jdbc.Driver";
dbname = "timegen";
username = "root";
password = "root";
connString = "jdbc:mysql://localhost:3306/" + dbname;
openConnection();
}
public void openConnection(){
try{
Class.forName(driverName);
con = DriverManager.getConnection(connString, username, password);
} catch(Exception e){
System.out.println(e);
}
}
public void terminateConnection(){
try{
con.close();
} catch(Exception e){
System.out.println(e);
}
}
public static Connector createConnection() {
if (connector == null){
connector = new Connector();
}
return connector;
}
public Connection getCon() {
return con;
}
public String getConnString() {
return connString;
}
public void setConnString(String connString) {
this.connString = connString;
}
}
This is the code for a class named MasterData, which is extended by all other classes that access the database
public class MasterData{
static Connector con;
static Statement st;
MasterData(){
try {
con = Connector.createConnection();
st = con.getCon().createStatement();
} catch (SQLException ex) {
Logger.getLogger(MasterData.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Statement createStatement() throws SQLException{
Statement st = con.getCon().createStatement();
return st;
}
public void closeConnection(){
con.terminateConnection();
}
}
An example of a class that uses this
public class Teacher extends MasterData{
int teacherid;
String teachername;
String subject;
String post;
#Override
public String toString() {
return "Teacher{" + "teacherid=" + teacherid + ", teachername=" + teachername + ",
post=" + post + ", subject=" + subject + '}';
}
public Teacher(int teacherid, String teachername,String subject, String post) {
this.teacherid = teacherid;
this.teachername = teachername;
this.subject = subject;
this.post = post;
}
public Teacher(String teachername) {
this.teachername = teachername;
}
public Teacher(){}
public String display(){
String s ="\nTeacher name = " + teachername
+ "\nSubject = " + subject
+ "\nPost = "+post;
return s;
}
public ArrayList<String> getSubjectTeachers(String s){
ArrayList<String> teachers = new ArrayList<String>();
try{
ResultSet rs = st.executeQuery("select teachername from teacher where
subject='"+s+"';");
while(rs.next()){
teachers.add(rs.getString(1));
}
}catch(Exception e){e.printStackTrace();}
return teachers;
}
public List<Teacher> getFree()
{
List<Teacher> lst = new ArrayList<Teacher>();
try{
ResultSet rs = st.executeQuery("select * from teacher where teacherid not
in(select classteacher from division where classteacher!=null)");
while(rs.next())
{
lst.add(new
Teacher(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4)));
}
}catch(Exception e ){e.printStackTrace();}
return lst;
}
public int getTeacherid() {
return teacherid;
}
public void setTeacherid(int teacherid) {
this.teacherid = teacherid;
}
public String getTeachername() {
return teachername;
}
public void setTeachername(String teachername) {
this.teachername = teachername;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public boolean checkDuplicate(){
try{
ResultSet rs = st.executeQuery("select * from teacher where
teachername='"+teachername+"';");
if(rs.next())
return true;
}catch(Exception e){e.printStackTrace();}
return false;
}
public boolean insert(){
int t;
try{
t = st.executeUpdate("insert into teacher(teachername,subject,post)
values('"+teachername+"','"+subject+"','"+post+"');");
if(t!=0) return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
return false;
}
public boolean delete(){
int t;
try{
new AssignedTeacher().deleteTeacher(teacherid);
t = st.executeUpdate("delete from teacher where teacherid="+teacherid+";");
if(t!=0) return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
return false;
}
public boolean update(){
int t;
try{
t = st.executeUpdate("update teacher set teachername = '"+teachername+"',
subject='"+subject+"', post='"+post+"' where teacherid="+teacherid+";");
if(t!=0) return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
return false;
}
}
My intention was to create a single static connection for the entire program. It seems to work well. But is this the possible cause of the problem?

Try to set these parameters as well:
-XX:PermSize
-XX:MaxPermSize

It looks like you are creating too many Connections.
You may verify whether or not your connection is valid in your openConnection method You also may use some Connection Pool.
EDIT:
It seems to me that you've tried to implement Active record pattern because there are insert, delete, update and getSubjectTeachers methods. Anyway, its is not always a good idea to extend Teacher from MasterData. As a side effect, new connections will be created for each instance of MasterData. static Connection con would be reassigned to new object but previous Connection will not be ever closed. Same holds with MasterData#createStatement.
Also, as greedybuddha pointed out, make sure that your HashMap are not reassigned in the same manner.

Related

"ORA-00933: SQL command not properly ended" Exception in this piece of code [duplicate]

This question already has answers here:
Why I obtain this "SQLSyntaxErrorException: ORA-00933: SQL command not properly ended" when I try to perform this JDBC query?
(4 answers)
Closed 1 year ago.
I am trying to connect to the Oracle 19c database from Java. Connection is done and successful.
I'm running same query in SQL Develeper and it's working .But I'm getting exception in prepared Statement and executeQuery() in Java. Please help me out.
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try{
//Loading Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Loading Connection
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/orcl",dbUsername,dbPassword);
//Executing query;
System.out.println("Connection Established");
//Object to store result
items=new ArrayList<Object>();
queryString="SELECT * FROM HOMESQUAD WHERE EMP_MOBILE_NO='8308856606';";
System.out.println("Query: "+queryString);
if(queryString != null && !queryString.trim().equals("")) {
System.out.println("Into P Statement If Loop");
pstmt=con.prepareStatement(queryString);
System.out.println("StateMent Prepared: "+pstmt.toString());
rs=pstmt.executeQuery();
System.out.println("Query Executed");
while(rs!=null &&rs.next()) {
items.add(constructLoginProps(rs));
}
if(rs !=null) {
rs.close();
}
if(pstmt!=null) {
pstmt.close();
}
}
}
catch(Exception e) {
System.out.println("Exception Occured in aDBExecute:"+e.getMessage());
}
//constructLoginProps Function
private HomesquadEmployee constructLoginProps(ResultSet rs) {
HomesquadEmployee vo=new HomesquadEmployee();
try {
if(rs.getString("EMP_PASSWORD")!=null) {
vo.setEmpPassword(rs.getString("EMP_PASSWORD"));
}
if(rs.getString("EMP_ID")!=null) {
vo.setEmpId(rs.getString("EMP_ID"));
}
if(rs.getString("EMP_NAME")!=null) {
vo.setEmpName(rs.getString("EMP_NAME"));
}
if(rs.getString("EMP_MOBILE_NO")!=null) {
vo.setEmpMobileNo(rs.getString("EMP_MOBILE_NO"));
}
}
catch(Exception e) {
System.out.println("Exception Occured in buildLoginQuery: "+e.getMessage());
}
return(vo);
}
//HomesquadEmployee Class
public class HomesquadEmployee {
private String empId;
private String empName;
private String empMobileNo;
private String empPassword;
public HomesquadEmployee() {
}
public HomesquadEmployee(String empId, String empName, String empMobileNo, String empPassword) {
this.empId = empId;
this.empName = empName;
this.empMobileNo = empMobileNo;
this.empPassword = empPassword;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpMobileNo() {
return empMobileNo;
}
public void setEmpMobileNo(String empMobileNo) {
this.empMobileNo = empMobileNo;
}
public String getEmpPassword() {
return empPassword;
}
public void setEmpPassword(String empPassword) {
this.empPassword = empPassword;
}
}
Output:
Connection Established
Query:SELECT * FROM HOMESQUAD_EMPLOYEE WHERE EMP_MOBILE_NO ='8308856606';
Into P Statement If Loop
StateMent Prepared: oracle.jdbc.driver.OraclePreparedStatementWrapper#51aeb3e7
Exception Occured in aDBExecute:ORA-00933: SQL command not properly ended
I had that problem once using an oracle database and I solved it by simply removing the semicolon ";" from the end of the query.
in your case you should change this
queryString="SELECT * FROM HOMESQUAD WHERE EMP_MOBILE_NO='8308856606';";
for this
queryString="SELECT * FROM HOMESQUAD WHERE EMP_MOBILE_NO='8308856606'";

How to pass the column name as dynamically in Postgres query in java

I want to pass the postgresql column names as dynamically on the execute query in java.I have created table and table name is product which has 4 columns(year, product,no,age).I have established the db connection and trying to pass the columns dynamically. I have created one pogo class which is having getter and setter of columns names.How can I pass the columns name dynamically on execute query.
dbcon.java
import java.sql.*;
import java.sql.Connection;
public class dbcon {
public static void main(String[] args) {
Connection conn =null;
Statement stmt = null;
DatabaseStatus databaseStatus = new DatabaseStatus();
try
{
Class.forName("******");
conn = DriverManager.getConnection("************", "*******", "*******");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select "+databaseStatus.getYear()+","+databaseStatus.getProduct()+","+databaseStatus.getNo()+","+databaseStatus.getAge()+" FROM \"Products\";");
while(rs.next()){
System.out.println(rs.getString("Year").trim());
System.out.println(rs.getString("Product").trim());
System.out.println(rs.getString("No.").trim());
System.out.println(rs.getString("Age").trim());
}
}
catch (Exception e) {
e.printStackTrace();
}finally {
try {
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
datastatus.java
public class DatabaseStatus {
private String No;
private String Year;
private String Product;
private String Age;
public String getNo() {
return No;
}
public void setNo(String no) {
No = no;
}
public String getYear() {
return Year;
}
public void setYear(String year) {
Year = year;
}
public String getProduct() {
return Product;
}
public void setProduct(String product) {
Product = product;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
Age = age;
}
}
table
SELECT "Year", "Product", "No.", "Age"
FROM "Products";
If you really want use the setters.
databaseStatus.setNo("No.");
databaseStatus.setYear( "Year");
databaseStatus.setProduct("Product");
databaseStatus.setAge("Age");
else remove the setters and
public class DatabaseStatus {
private String No = "No.";
private String Year = "Year";
private String Product = "Product";
private String Age = "Age";
public String getNo() {…
}

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.

What is the logic of creating the Mysql SELECT Statement for drop down in Struts + JSP?

can you please help me rectify the code below, I'm trying to create a populated drop down list in struts 2 in Eclipse as my IDE. This is my first time to use 'STRUTS' as well as 'IDE ECLIPSE'.
To be specific by the SELECT statement I do not know how to write the code that, when a user selects the 'Make' of the car, the database extracts the different 'Models' of that make. But other select items like 'Color', should be optional in that a user can proceed to search for the 'Make' minus choosing an option from them.
Please help I'm new in ActionClass and DataBase. Thanx in advance.
package drive;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.opensymphony.xwork2.ActionSupport;
public class CarSearch extends ActionSupport {
private String model;
private String modification;
private String engine;
private String color;
private String bodyType;
private String minPrice;
private String maxPrice;
private String mileage;
private int minYear;
private int maxYear;
private String make;
public String execute () {
String ret = NONE;
Connection conn = null;
try {
String URL = "jdbc:mysql://localhost/Cars";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, "root", "$jademedia247");
String sql = "SELECT make FROM type WHERE";
sql+=" model = ? AND modification = ? ";
PreparedStatement ps = conn.prepareStatement (sql);
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
while (rs.next()){
make = rs.getString(1);
ret = SUCCESS;
}
} catch (Exception e) {
ret = ERROR;
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return ret;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getModification() {
return modification;
}
public void setModification (String modification) {
this.modification = modification;
}
public String getEngine() {
return engine;
}
public void setEngine (String engine) {
this.engine = engine;
}
public String getColor() {
return color;
}
public void setColor (String color) {
this.color = color;
}
public String getBodyType() {
return bodyType;
}
public void setBodyType(String bodyType) {
this.bodyType = bodyType;
}
public String getMinPrice() {
return minPrice;
}
public void setMinPrice(String minPrice) {
this.minPrice = minPrice;
}
public String getMaxPrice () {
return maxPrice;
}
public void setMaxPrice (String maxPrice) {
this.maxPrice = maxPrice;
}
public String getMileage () {
return mileage;
}
public void setMileage (String mileage) {
this.mileage = mileage ;
}
public int getMinYear() {
return minYear;
}
public void setMinYear(int minYear) {
this.minYear = minYear;
}
public int getMaxYear() {
return maxYear;
}
public void setMaxYear(int maxYear) {
this.maxYear = maxYear;
}
public String getMake() {
return make;
}
public void setMake(String make){
this.make = make;
}
}
PreparedStatement ps = conn.prepareStatement ("SELECT field_name FROM table_name WHERE model = ? AND modification = ? ");
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
//it will help you

Throws Exception in netbeans when using GET

I'm trying to retrieve data from my Model class into textfield via GET, although nullpointexception is throwing an error
The code in the View class is =
public View_EditCustomer(Model_Customer cust) {
customer = cust;
txtname.setText(customer.GetFName());
txtSecondName.setText(customer.GetLName());
initComponents();
}
and in another View class it is =
private void btnSelectActionPerformed(java.awt.event.ActionEvent evt) {
ListSelectionModel rowSM = jTable1.getSelectionModel();
int row = rowSM.getMinSelectionIndex();
int Appointment_ID = (Integer)resultModel.getValueAt(row, 0);
Model_Customer cust = null;
try{
cust = Controller_ManageCustomer.GetCustomer(Appointment_ID);
new View_EditCustomer(cust).setVisible(true);
}catch(Exception ex){
JOptionPane.showMessageDialog(this,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
Model_Customer code parts =
public static Model_Customer QueryID(int Appointment_ID) throws Exception
{
try{
Statement stmt = Model_Customer.conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM appointment WHERE appointmentid="+Appointment_ID+" LIMIT 1;");
if(rs.next())
return new Model_Customer(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11),rs.getString(12));
}catch(Exception e){
throw new Exception(e.getMessage());
}
return null;
}
private Model_Customer(int Appointment_ID, String FName, String LName, String Registration, String Make, String Model, String Engine, String Year, String Mileage, String Type, String Date, String Time)
{
this._Appointment_ID=Appointment_ID;
this._Type=Type;
this._Time=Time;
this._Date=Date;
this._FName=FName;
this._LName=LName;
this._Make=Make;
this._Model=Model;
this._Engine=Engine;
this._Year=Year;
this._Mileage=Mileage;
this._Registration=Registration;
this._inSync=true;
}
public int GetID()
{
return this._Appointment_ID;
}
public String GetFName()
{
return _FName;
}
public String GetLName()
{
return _LName;
}
public String GetRegistration()
{
return _Registration;
}
public String GetMake()
{
return _Make;
}
public String GetModel()
{
return _Model;
}
public String GetEngine()
{
return _Engine;
}
public String GetYear()
{
return _Year;
}
public String GetMileage()
{
return _Mileage;
}
public String GetType()
{
return _Type;
}
public String GetDate()
{
return _Date;
}
public String GetTime()
{
return _Time;
}
In debugging Model_Customer cust is actually populated by data and it actually goes to the end to txtname.setText(customer.GetFName()); goes to Model_Customer GetFName and should retrieve the name but throws an exception (int)0. Would really appreciate your help!!
Shouldn't initComponents(); be called before using TextViews ?
public View_EditCustomer(Model_Customer cust) {
initComponents();
customer = cust;
txtname.setText(customer.GetFName());
txtSecondName.setText(customer.GetLName());
}

Categories