Stuck on syntax pushing an object built into an array - java

Attempting to push this object that I'm building my while loop into a list array. I can't exactly figure out what I'm doing wrong. Can some one please explain first, what the best syntax is and the best way to pull out this information to push it to a list array. so later I can access the list array by getting the information out of it.
public void getTableConnection() throws ClassNotFoundException,
SQLException {
List<Car>cars = new ArrayList<Car>();
Car car = new Car();
try {
Table table = new Table();
table.getTableConnection();
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/carrentalsystem";
String username = "root";
String password = "javatest";
String query = "select * from cardetails";
Connection conn = DriverManager.getConnection(url, username,
password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
car.setId(rs.getInt("id"));
car.setYear(rs.getString("Year"));
car.setMake(rs.getString("Make"));
car.setModel(rs.getString("Model"));
car.setColor(rs.getString("Color"));
car.setAvailable(rs.getString("Availability"));
String renting;
car.add()
}
return cars;
}catch(Exception e) {
}finally{
}
}

I had to change that line to cars.add(car)

At the first place you didn't add car to cars.You can't change the value of the returned ArrayList (cars) in the finally block if it is already returned. So don't return from try.

Related

Query data and pass as input for another function in a loop Java

I am writing an application that required to query data from oracle database and send each queried data as input to another function in java. I am not sure how to pass those queried data as input to another function. I am trying to use Arraylist but still could not able to pass as input. Any help will be appreciated. Hope to hear from you all.
String dbuserName = "";
String dbpassword = "";
String url = "jdbc:oracle:thin:#//xxxxxxxxxxxxxx";
String driverName = "oracle.jdbc.driver.OracleDriver";
Connection conn = null;
Session session = null;
try{
// Some Connection code to database here before below code
Statement stmt = conn.createStatement();
ResultSet rs = stat.executeQuery( "SELECT ..." );
ArrayList <String[]> result = new ArrayList<String[]>();
/*Queried data has only one column, that is useid, now need to
send each id as input to below try/catch statement*/
try {
userManager.enable(USER_LOGIN, true);
System.out.print("\n Enabled user Successfully");
} catch (ValidationFailedException e) {
e.printStackTrace();
logger.severe("ValidationFailedException: " + e ");
}
This will help you
while (rs.next()) {
int i = 1;
result.add(rs.getString(i++));
}
Then in the for loop
for(int i=0;i<result.size()-1;i++)
{
String USER_LOGIN=result.get(i);
userManager.enable(USER_LOGIN, true);
}

Displaying datatable from database

I am trying to display data from the database into a datatable and I am getting no results. I tested the queries with JDBC with exact select statement to see if it returns any row, and it always worked. But when I try to have the data from the database into my datatable I get no results. I even made a fake dummy data just to populate my datatable. I must be doing something wrong in the index.xhtml file that I don't know of. What could I doing wrong ? any help would be appreciated ?
edit: first I went to with Primefaces with their datatable example, and than I went with simple jsf style datatable like I have here and neither of those worked when I try to do it with the database
UserDAO.java
public class UserDAO {
private static final String USERNAME = "something";
private static final String PASSWORD = "something";
private static final String CONN_STRING =
"jdbc:sqlserver://petunia.arvixe.com.....something";
public List<Report> getUserList() {
List<Report> list = new ArrayList<Report>();
PreparedStatement ps = null;
Connection con = null;
ResultSet result = null;
try {
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
while (result.next()) {
Report rep = new Report();
rep.setId(result.getInt("id"));
rep.setTag(result.getString("tag"));
rep.setName(result.getString("asset_name"));
rep.setModel(result.getString("model"));
rep.setSerial(result.getString("ser_no"));
rep.setValue(result.getFloat("value"));
rep.setCondition(result.getString("asset_condition"));
rep.setType(result.getString("asset_type"));
rep.setLocationName(result.getString("name"));
rep.setAddress(result.getString("address"));
rep.setCity(result.getString("city"));
rep.setState(result.getString("state"));
rep.setZip(result.getString("zip"));
rep.setPhone(result.getString("phone"));
rep.setDistrict(result.getInt("district"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
}
Well, you are making a report:
Report rep = new Report();
...but not adding it to your list. Add this:
Report rep = new Report();
list.add(rep);
I suppose your problem is this code:
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You are overwriting your sql statement immediately with the statement sql1.
I think, you probably want to select the assets with THEIR locations. In SQL you can use a JOIN to achieve that.
If you use this syntax
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You will get as a result only the execution of the second query. I think that in your case you are trying to get a result from both tables assets and location so you should use a join between the 2 tables.

A lock could not obtained within the time requested issue

The title is the error I'm getting, when I click load my program freezes. I assume it's because I'm doing a statement inside a statement, but from what I see it's the only solution to my issue. By loading, I want to just repopulate the list of patients, but to do so I need to do their conditions also. The code works, the bottom method is what I'm trying to fix. I think the issue is that I have 2 statements open but I am not sure.
load:
public void DatabaseLoad()
{
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
PatientList.clear();
Statement stmt8 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL8 = "SELECT * FROM PATIENTS";
ResultSet rs8 = stmt8.executeQuery( SQL8 );
ArrayList<PatientCondition> PatientConditions1 = new ArrayList();
while(rs8.next())
{
PatientConditions1 = LoadPatientConditions();
}
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTS";
ResultSet rs = stmt.executeQuery( SQL );
while(rs.next())
{
int id = (rs.getInt("ID"));
String name = (rs.getString("NAME"));
int age = (rs.getInt("AGE"));
String address = (rs.getString("ADDRESS"));
String sex = (rs.getString("SEX"));
String phone = (rs.getString("PHONE"));
Patient p = new Patient(id, name, age, address, sex, phone,
PatientConditions1);
PatientList.add(p);
}
UpdateTable();
UpdateAllViews();
DefaultListModel PatientListModel = new DefaultListModel();
for (Patient s : PatientList) {
PatientListModel.addElement(s.getAccountNumber() + "-" + s.getName());
}
PatientJList.setModel(PatientListModel);
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
}
This is the method that returns the ArrayList of patient conditions
public ArrayList LoadPatientConditions()
{
ArrayList<PatientCondition> PatientConditionsTemp = new ArrayList();
try
{
String Name = "Wayne";
String Pass= "Wayne";
String Host = "jdbc:derby://localhost:1527/Patients";
Connection con = DriverManager.getConnection( Host,Name, Pass);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM PATIENTCONDITIONS";
ResultSet rs5 = stmt.executeQuery( SQL );
int e = 0;
while(rs5.next())
{
e++;
String ConName = (rs5.getString("CONDITION"));
PatientCondition k = new PatientCondition(e,ConName);
PatientConditionsTemp.add(k);
}
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
return PatientConditionsTemp;
}
I had a similar problem.
I was connecting to derby db hosted on local server.
I created 2 simultaneous connections:
With squirrel
With ij tool
When a connection makes a modification on a table, it first gets a lock for the particular table.
This lock is released by the connection only after committing the transaction.
Thus if the second connection tries to read/write the same table, a msg prompts saying:
ERROR 40XL1: A lock could not be obtained within the time requested
To fix this, the connection which modified the table has to commit its transaction.
Hope this helps !
Here is a good place to start: http://wiki.apache.org/db-derby/LockDebugging
You need to close your statement and result set as well so that when you restart your program they won't be open. Add stmt.close(); and rs.close(); at the end of your lines of code within the try and catch statement.
Why could you not use the same connection object to do both the queries?
Like pass that connection object to the LoadPatientConditions() as a parameter and use it there.

Java user class

How I can resolve java user class and JDBC user class? The problem is when i run out put is ther is data in sql.For example
public User authenctication(String eMail, String password) {
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "root");
stm = con.createStatement();
rs = stm.executeQuery("select * from User,Role where user.id=role.id");
while(rs.next()) {
user = new User();
user.setAddress(rs.getString(""));
user.setCountry(rs.getString(""));
user.setCreatedBy(rs.getString(""));
user.setEMail(rs.getString(""));
user.setId(rs.getInt(""));
}
} catch (Exception sqlEx) {
System.out.println("sqlexecuteException: " + sqlEx.toString());
}
return user;
}
user = new User();
Everytime you assign a new Object to user, you loose the old. A better possibility would be the usage of a LinkedList:
List<User> users = new LinkedList<User>();
while (rs.next()) {
User user = new User();
user.setAddress(rs.getString(""));
user.setCountry(rs.getString(""));
user.setCreatedBy(rs.getString(""));
user.setEMail(rs.getString(""));
user.setId(rs.getInt(""));
users.add(user);
}
The code above seems to be wrong. You are trying to create and initialize the same object
user = new User();
again and again all over the result set. Instead use an Array List
public User authentication(String eMail, String password) {
try {
ArrayList<User> user_set = new ArrayList<User>();
con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "root");
stm = con.createStatement();
rs = stm.executeQuery("select * from User,Role where user.id=role.id");
while(rs.next()) {
user = new User();
user.setAddress(rs.getString(""));
user.setCountry(rs.getString(""));
user.setCreatedBy(rs.getString(""));
user.setEMail(rs.getString(""));
user.setId(rs.getInt(""));
user_set.add(user);
}
} catch (Exception sqlEx) {
System.out.println("sqlexecuteException: " + sqlEx.toString());
}
return user_set;
}
Give the Fully-Qualified Name of a class to avoid Naming Conflicts.
For Ex :
com.me.package.User objUser = new com.me.package.User();
Where User is the class which resides in the package com.me.package
Try to look at more closely to your query ,it seems wrong to me .
Also use Prepared Statement to avoid Sql Injection
I think you want only one user to be logged in. For that, your query is wrong.
You should make it like this:
"SELECT * FROM User,Role WHERE (user.id=role.id) AND (user.email='" + eMail + "')"
This will give you only the user with the email address you passed.
But there is another way to achive your goal without risking a SQL injection. You could leave your program as it is. You only add one simple line in your loop, just before the closing brace:
if (user.getEMail().equals(eMail))
break;
This line will make it possible to exit the loop after the right user was found. So you will return the right one.

DB query not populating to combo box...why?

I've been at this for awhile and have tried different examples (including a few that I found here), and tried to adapt them to what I need.
I am trying to use a DB query in a servlet to populate a combo box in the resulting html form that is created. While it all compiles and the page pops up with a combobox, there is nothing in the box to choose from, which tells me that something is wrong with how I am passing variables.
I've basically narrowed my methods down to two, but get the same results from both.
Can someone have a look-see and give me a clue?
out.print(`"<tr><td>SoldWhich Home ID: `</td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
ArrayList<String> soldWhich = new ArrayList<String>();
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String[])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
And the other method:
out.print(`"<tr><td>SoldWhich Home ID: </td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try{
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home ORDER BY home_id";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
soldWhich.add(rs1.getString(1));
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String [])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
Where are you setting "home_id" request attribute and why are you even setting it? I think you should take out the following line of code and see if it works. Modify your code to this.
List<String> soldWhich = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
I think you are not actually getting values (sh) in the "for(String sh : soldWhich)" loop. Can you try printing the values in a simple table just to see if you actually get data? Also why aren't you using jstl to perform this task? And your catch block does not log any errors either in case you are actually getting some sort of errors that will go unnoticed.

Categories