My information is read in via CSV for "banking information", A person CSV is
5
1,Tony,Stark,C,tonys,naslvj34-t934,stark#hmmm.org;tony#gmail.com;tostark55#yaho.com
2,Patrick,Hart,C,phart2,sdlwgl5034i52,hart#hmmm.org;hart1#who.org
3,Tom,Baker,E,bake95,kweojtnefq567,
4,Kevin,Black,C,keb765,prjhohier99,black#mail.org
5,Alex,Codd,E,alcodd,andlqjr78,codd#DBMS.org;alex#gmail.com
my Account CSV is,
5
1,313001,S,35881.12
2,313002,G,772400.34
3,313003,C,250002.15
4,313004,P,96310.66
5,313005,P,15624.15
1,313006,C,39950.99
In the Account CSV the 2nd token is My "Account type", so S = "Savings" G = "Gold Savings" C = "Checkings" and so on. When reading these in my CSV parser class, an object was made of the types, so A Checking class was made and when the CSV was tokenized when token[2] was equal to "C".
My Persons class is set up as so, excluding my getters and setters
private int personId;
private String firstName;
private String lastName;
private String type;
private String usrname;
private String password;
private ArrayList<String> emails;
public Person(int personId, String firstName, String lastName, String type, String usrname, String password,
ArrayList<String> emails) {
super();
And my Account class is set up as so.
private Person accountHolder;
private int accountNumber;
private double currentBalance;
public Account() {}
public Account(Person accountHolder, int accountNumber, double currentBalance) {
this.accountHolder = accountHolder;
this.accountNumber = accountNumber;
this.currentBalance = currentBalance;
}
This is one of my example account types (there are multiple)
public class CheckingAccount extends Account {
public CheckingAccount(Person p, int i, double d) {
super(p,i, d);
}
This is my database adder
public static void DbAddAccount(Person personId, Account accountHolder){
Connection conn = null;
try {
conn = DriverManager.getConnection(DatabaseInfo.URL, DatabaseInfo.USERNAME, DatabaseInfo.PASSWORD);
} catch (SQLException e) {
System.out.println("Connection Failed");
throw new RuntimeException(e);
}
String accountQuery = "insert into Account (accountId,accountNumber,currentBalance,type,personId) values (?,?,?,?,?);";
PreparedStatement accountPs = null;
ResultSet accountKeys = null;
int accountId = 0;
try {
//These are my prepare Statements for my queries
accountPs = conn.prepareStatement(accountQuery);
accountPs.setInt(1, accountId+ 1 );
accountPs.setInt(2, accountHolder.getAccountNumber());
accountPs.setDouble(3, accountHolder.getCurrentBalance());
accountPs.setString(4, ??????????????????????????????????);
accountPs.setInt(5, personId.getPersonId());
accountPs.executeUpdate();
accountPs.close();
conn.close();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JDBC is not adding anything when running.
I think your code has following issues:
Account Object:
Object is missing field to store "Account Type"
Setting incorrect account type in DbAddAccount method
At line accountPs.setString(4, ??????????????????????????????????);
you are number of question marks (without enclosing in quote to make string) as account type which appears it is not correct.
series of ??? wont get converted to string without enclosed in quotes.
Even if you enclose in quotes, I think it wont be intended account number;
Solution
for Issue 1; declare account_type in Account Object.
for issue 2; instead of using accountPs.setString(4, ??????????????????????????????????);
use:
accountPs.setString(4, account.getAccountType());
Related
guys, i stuck into the middle on process writing my own first web-app. I have a couple issues with DAO layer.
Look at my first entity:
public class Fabric {
private Integer id;
private String name;
private String country;
}
There is Object, which "id" property is the foreign key for another entity:
public class Guitar {
private Integer id;
private Fabric fabric;
private String name;
private Short strings;
private Color color;
private Integer count;
}
So when i try to write DAO layer for "Guitar" entity like this:
Guitar guitar = null;
try (Connection connection = ConnectionManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(GET_BY_ID)) {
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
guitar = Guitar.builder()
.id(resultSet.getInt(id))
***.fabric()*** <---- idk how to get fabric id
.name(resultSet.getString("name"))
.strings(resultSet.getShort("strings"))
.color(???some jave code???) <--- this is ENUM :(
.count(resultSet.getInt("count"))
.build();
}
} catch (SQLException e) {
throw new DaoException(e);
}
return Optional.ofNullable(guitar);
} ``
SQL request: ```private static final String GET_BY_ID = "SELECT id, fabric_id, name, strings, color, count FROM shop_storage.guitar WHERE count NOTNULL";
p.s. also idk how to get enum in this object:(
If can help me - i'll appreciate it.
have a good time anyone:)
Im writing code that needs to take a file input and then reconstruct the values into an ArrayList.
This is the code ive done so far to convert a file to an object.
public static ArrayList<User> fileToObject() {
ArrayList<User> FileToObject = new ArrayList<>();
Scanner in = null;
boolean err0 = false;
try {
in = new Scanner(Paths.get("User_info.txt"));
} catch (IOException ex) {
err0 = true;
}
if (!err0) // if couldn't open file then skip
{
while (in.hasNext()) {
String theUser = in.nextLine();
String[] Line = theUser.split(",");
User user = null;
try {
if ( Line.length == 10) {
// reconstruct Address
Address a1 = new Address( Line[2], Line[3], Line[4], Line[5], Line[6],
Integer.parseInt( Line[7]));
// reconstruct Customer
user = new Customer( Line[0], Line[1], Line[2], Line[3], Line[4], Line[5], Line[6], Line[7],a1, Line[14]);
FileToObject.add(user);
} else {
return null;
}
} catch (NoSuchElementException ex) {
System.out.println("File improperly formed. Terminating.");
}
}
in.close();
}
// write object back to file.
File f1 = new File(Paths.get("User_info.txt").toUri());
Formatter out = null;
boolean err = false;
try {
out = new Formatter(f1);
} catch (FileNotFoundException ex) {
err = true;
}
if (!err) {
//System.out.println(e3.size());
for (User i : FileToObject) {
out.format("%s%n", i.toString()); // output the card object to cvs format
}
out.close();
}
}
}
My issue here is that element Line[5] of the array User( user = new Customer(Line[0], Line[1], Line[2], Line[3], Line[4], Line[5)) is of Type enum(as seen in the first constructor of the below customer class) so i get an error "Incompatible Type, String cannot be converted to UserType(UserType being the Enum).
import java.util.ArrayList;
public class Customer extends Billing {
Address customerAddress;
public Customer(String id, String firstName, String lastName, String userName, String password, UserType userType, PermissionType permission, Boolean Status, Address billingAddress, String email, Address customerAddress) {
super(id, firstName, lastName, userName, password, userType, permission, Status, billingAddress, email);
this.customerAddress = customerAddress;
permission = PermissionType.Booking;
userType = UserType.VIP;
setId(id);
setPermission(permission);
setCustomerAddress(billingAddress);
}
public Customer(String id, String firstName, String lastName, String userName, String password, UserType userType, PermissionType permission, Boolean Status, Address billingAddress, String email) {
super(id, firstName, lastName, userName, password, userType, permission, Status, billingAddress, email);
}
public Address getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(Address customerAddress) {
this.customerAddress = customerAddress;
}
I spoke to my Tutor and he told me i need to convert the String to an Enum. Im unsure of what he meant by this as he wouldnt explain any Further. Is he talking about the String Array or do i need to convert the String within the file im reading to an enum? Im a bit lost so any help is greatly appreciated
If UserType is an enum, you can convert it with the static UserType.valueOf() method, i.e.:
UserType userType = UserType.valueOf(Line[5]);
Now you can use userType in place of Line[5] in the following code.
Note that Line[5] must exactly match the spelling of any of the enum types, or an IllegalArgumentException will be thrown.
If UserType.valueOf could not provide what you need, add a static method that returns specific UserType instance. For example:-
public enum UserType{
CUSTOMER("customer");
private String name;
UserType(String name){
this.name = name;
}
//A Map that holds user type name as key.
private static Map<String,UserType> userTypeMap = new HashMap<>();
//Populate userTypeMap with UserType instance
static{
for(UserType type : values()){
userTypeMap.put(type.name, type);
}
}
public static UserType of(String name){
return userTypeMap.get(name);
}
}
Callers could get UserType instance as below:-
UserType type = UserType.of("customer");
your solution is so long. there is an elegant way of doing this
Properties properties = new Properties();
properties.load(new FileInputStream(new File("FileLocation")));
properties.values();
File can contain, list of values, key value pairs. At line no 2 file is loaded in Properties object. Now u can process it according to your need.
I have following java class
package com.picvik.model;
import java.util.Date;
public class ViewAlbum {
private Integer albumid;
private String albumname;
private String description;
private String location;
private Date date;
private Integer uid;
public Integer getAlbumid() {
return albumid;
}
public void setAlbumid(Integer albumid) {
this.albumid = albumid;
}
public String getAlbumname() {
return albumname;
}
public void setAlbumname(String albumname) {
this.albumname = albumname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
}
I am retrieving data from db and adding it to my array list like this
public ArrayList getAllAlbums(Integer uid) {
ViewAlbum album = new ViewAlbum();
ArrayList<ViewAlbum>allAlbums = new ArrayList<ViewAlbum>();
try {
String qstring = "SELECT albumid, albumname, description, location," +
" date, uid FROM picvik_picture_album WHERE " +
"uid = '" + uid + "';";
System.out.println(qstring);
connection = com.picvik.util.MySqlConnection.getInstance().getConnection();
ptmt = connection.prepareStatement(qstring);
resultSet = ptmt.executeQuery();
while(resultSet.next()) {
//System.out.println(resultSet.getString("albumname"));
album.setAlbumid(resultSet.getInt("albumid"));
album.setAlbumname(resultSet.getString("albumname"));
album.setDescription(resultSet.getString("description"));
album.setLocation(resultSet.getString("location"));
album.setDate(resultSet.getDate("date"));
album.setUid(resultSet.getInt("uid"));
allAlbums.add(album);
}
resultSet.close();
ptmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return allAlbums;
}
But when I am trying to print the values stored in array list. Its always giving me the last inserted record.
<div class="row">
<div class="span10">
<s:iterator value="allAlbums">
<s:property value="albumname"/>
</s:iterator>
</div>
</div>
Here,
ViewAlbum album = new ViewAlbum();
// ...
while (resultSet.next()) {
album.setAlbumid(resultSet.getInt("albumid"));
// ...
allAlbums.add(album);
}
you're reusing the very same album instance for all records. The instance's data get overridden everytime in the loop. The list does not contain copies of the instance, but it contains copies of the reference to the single instance. You know, Java is Object Oriented.
You should be creating a new album instance per record. Move the instantiation to inside the loop.
// ...
while (resultSet.next()) {
ViewAlbum album = new ViewAlbum();
album.setAlbumid(resultSet.getInt("albumid"));
// ...
allAlbums.add(album);
}
See also:
How can I pass an Integer class correctly by reference?
Unrelated to the concrete problem, you should be closing JDBC resources in the finally block, or be opening them in the try() try-with-resources statement, otherwise they will still leak away in case of an exception during executing the query or processing the result set. You should also move the declarations of JDBC resources to inside the method block, otherwise you'll run into threadsafety issues as well. Last but not least, you should use the setter methods of PreparedStatement to set user-controlled variables in a SQL string. If they were strings, you'd have a SQL injection attack hole.
See also:
Java Iterator backed by a ResultSet
JDBC MySql connection pooling practices to avoid exhausted connection pool
You have only one instance of ViewAlbum and you are playing(setting the values) only with that single instance throughout the loop. So after completition of loop you have only one object inserted into ArrayList for N(Size of Resultset) no of times.
I'm making a mysql database connector with java to show all the data.
When I run the code, I get an NullPointerException in my getData() function.
here is my code.
public String[][] getData() {
String values[][];
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values[i][0] = id;
values[i][1] = name;
values[i][2] = adress;
values[i][3] = catagory;
i++;
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
When the value of the String values is nothing I get The error. But if I give the String allready a value it says nothing .
public String[][] getData() {
String values[][] = {{"","","",""},
{"","","",""},
{"","","",""},};
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values[i][0] = id;
values[i][1] = name;
values[i][2] = adress;
values[i][3] = catagory;
i++;
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
I want more data than that in my data String. how can I let it automatically do that??
Tnx.
PS.
The function is called in my class FrameGUI and has to change to Object
public class FrameGUI extends JFrame {
public JTable dataHolder;
Mysql mysql = new Mysql();
public String[] columnNames = {
"ID", "Name", "Adress", "Catagory"
};
-> public Object[][] data = mysql.getData();
public FrameGUI() {
init();
mysql.getData();
}
}
You do not initialize String values[][] so it is null. You either need to initialize it first or use a more appropriate datastructure like a List.
You should define a class and use a List (e.g. the ArrayList) instead.
e.g. if you want to call it User -
public class User {
private String id;
private String name;
//...
}
and a list
List<User> users = new ArrayList<User>();
and then instantiate the User class for each row and add the new instance to the list -
User currUser = new User();
users.add(currUser);
//set values from result set
The list can grow automatically when needed and the code is much more readable than using the array.
You get an index out of bounds in the first example because a String[][] (or String Matrix) gets initialized as a zero-length array.
In the second instance, you initialized the array to a size of 3x4 - that works so long as you only get 3 results back.
What you really need is a data structure with a dynamic size. Arrays aren't automatically sized dynamically. Try using a collection implementation like ArrayList or LinkedList or Vector.
Also, instead of saving your values to a String[], try creating a bean class that can hold your result. Create a new instance of it for each result that you get back instead of initializing a new array.
Because you didn't initialized your array, that is why you get NPE. Actually I suggest you to use List for your purposes:
public ArrayList<ArrayList<String>> getData() {
ArrayList<ArrayList<String>> values = new ArrayList<>();
try {
rs = st.executeQuery("SELECT * FROM adresses");
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
ArrayList<String> list = new ArrayList<>();
list.add(id);
list.add(name);
list.add(adress);
list.add(catagory);
values.add(list);
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
The main problem in you code is you are using arrays to save variable number of data. Arrays is fixed sized after they are created so you can't add (or remove) elements to them dynamically.
Instead of using arrays you should use an ArrayList object which have methods to add more elements. Also instead of creating a multidimensional array it looks like a better idea to create a class for the data you get from you database.
So lets first create a Address class:
public class Address {
public String id, name, adress, catagory;
public Address(String id, String name, String adress, String catagory) {
this.id = id;
this.name = name;
this.adress = adress;
this.catagory = catagory;
}
}
Now you can write you code as:
public List<Address> getData() {
List<Address> values = new ArrayList<Address>();
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values.add(new Address(id, name, adress, catagory));
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
The returned list will contain a list of Address objects which have the values from you database. Also, the size of the list is always the same as the content you put into it.
Hi while developing one of my web application i am storing the user information in to an ArrayList based on sql query executed, it contain duplicate objects how to remove duplicate objects in list , i already tried some method but it still not working.
This Is My Code Correct me where i am wrong
public ArrayList loadData() throws ClassNotFoundException, SQLException {
ArrayList userList = new ArrayList();
String url = "";
String dbName = "";
String userName = "";
String password = "";
Connection con = null;
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement ps = null;
try {
String name;
String fatherName;
int Id;
String filePath;
int age;
String address;
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString(1);
fatherName = rs.getString(2);
age = rs.getInt(3);
address = rs.getString(4);
Id = rs.getInt(5);
filePath=rs.getString(6);
/* if(flag)
{
prev=Id;
flag=false;
}
else if(Id==prev)
{
TEMP=TEMP+";"+filePath;
}*/
//PhotoList = PhotoList(Id, con);
UserData list = new UserData();
list.setName(name);
list.setFatherName(fatherName);
list.setAge(age);
list.setAddress(address);
list.setId(Id);
// list.setFilePath(filePath);
userList.add(list);
}
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
ArrayList al = new ArrayList();
HashSet hs = new HashSet();
hs.addAll(userList);
al.clear();
al.addAll(hs);
return al;
}
And My Bean Class contant is
public class UserData {
private String name;
private String fatherName;
private int Id;
//private String filePath;
private int age;
private String address;
public UserData()
{
}
public UserData(String name, String fatherName,int Id, int age,String address)
{
this.name = name;
this.fatherName = fatherName;
this.Id = Id;
//this.filePath=filePath;
this.age=age;
this.address=address;
}
//GETTER AND SETTER..
General Idea: Use Set, not List. But you must override hash and equals of the class.
If you want a Collection of objects that does not have a specific order and you don't want duplicates, it's better for you just to use a Set like for example HashSet, or, if in your set the order is important, the TreeSet.
Just remember to override the hash and equals methods.
if you add this to your bean everything should work:
public int hashCode() {
return (name + fatherName+ Id + filePath + age + address).hashCode();
}
public boolean equals(Object obj) {
return ( hashCode() == obj.hashCode() );
}
Your userdata class does not implement equals or hashcode. This means two instances created with the same values will not be counted as duplicates. This is why the set contains duplicates.
For example
UserData u1 = new UserData("Foo", "bar",1, 1,"baz");
UserData u2 = new UserData("Foo", "bar",1, 1,"baz");
u1 and u2 are not considered equal as they are different objects. Adding an equals and hashcode method should fix this. However even better is adarshr's idea of removing dupes in the SQL.
All duplicates must be removed at an SQL level. Your SQL is suggesting that it could be generating duplicate records.
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
What does the clause ID = USER_ID mean? Shouldn't you be passing in that value as an input to your query?
Also, is the column ID a primary key? Otherwise, use a where clause that doesn't generate duplicates.