So I am creating an online bank transfer section where the user can transfer money between their account. I have a drop down box where it will show the amount of accounts the user has. I am not sure if I am doing this correctly. Here is my code so far:
transfer-page.jsp
<form name="transfer" action="TransferServlet" method="post">
<%
String email = (String) session.getAttribute("email");
String getAccountType = UserProfileService.getAccountTypeByEmail(email);
int count = UserProfileService.getAmountOfAccounts(email);
%>
From Account: <select name="AccountType">
<%
for(int i = 0; i < count; i++)
{
%>
<option> <%=getAccountType %>
<%
}
%>
</option>
</select>
</form>
Database Class:
public static String getAccountTypeByEmail(String email)
{
// AccountType accountType = new AccountType();
String getAccountType = "";
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT * FROM accountType WHERE email=?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, email);
ResultSet rs = stmt.executeQuery(query);
rs.next();
getAccountType = rs.getString("accountType");
// accountType.setAccountType(getAccountType);
} catch (Exception e)
{
System.out.println(e);
}
// return accountType;
return getAccountType;
}
public static int getAmountOfAccounts(String email)
{
int count = 0;
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT count(*) FROM accountType WHERE email=?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, email);
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
String account = rs.getString("accountType");
count++;
}
} catch (Exception e)
{
System.out.println(e);
}
return count;
}
I do not know under what circumstances you will appear in the drop-down box shows the amount of the account. An account binding more than one bank card?
String getAccountType = UserProfileService.getAccountTypeByEmail(email); your method getAccountTypeByEmail(String email) return only one result,why you loop show it.
Related
hi my program work in back ground and show different message from database
in specific time the problem always show the same row
//////
**upload code **
public void myMethod(){
long startTime = System.currentTimeMillis();
int counter = 0;
while(true) {
if((System.currentTimeMillis() - startTime ) == 5000){
try{
String host = "jdbc:derby://localhost:1527/Quet";
String uName = "eenas";
String uPass= "2234";
con = DriverManager.getConnection( host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery( "SELECT * from EENAS.EENAS");
rs.next();
int id_col = rs.getInt("ID");
String id =Integer.toString(id_col);
String me=rs.getString("MESSAGE");
System.out.print(me);
rs.close();
}
catch(SQLException err)
{
JOptionPane.showMessageDialog(null, err);
}
startTime = System.currentTimeMillis();
continue; }
else{ continue; } } }
upload code
the can solve this problem by using arrayList to save all data, your program now show only that last one because they change their value every time, the solution like this,
public void DoConnect( ) {
try{
String host = "jdbc:derby://localhost:1527/Quet";
String uName = "eenas";
String uPass= "2234";
con = DriverManager.getConnection( host, uName, uPass);
stmt = con.createStatement();
rs = stmt.executeQuery("select * from EENAS.EENAS");
List<String> PMessage = new ArrayList<String>();
List<Integer> id_col = new ArrayList<Integer>();
while(rs.next()){
id_col.add(rs.getInt("ID"));
PMessage.add(rs.getString("MESSAGE"));
jTextArea1.setText(PMessage);
}
rs.close();
stmt.close();
con.close();
}
catch(SQLException err)
{
JOptionPane.showMessageDialog(null, err);
}
}
I didn't run the code on my machine but this is the logic can solve the problem.
I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java
<%# page import= "java.sql.*"
import= "java.util.*"%>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
Statement st = con.createStatement();
String name = request.getParameter("name");
String username = request.getParameter("user");
String pass = request.getParameter("pas");
String cpass = request.getParameter("cpas");
String sql2 = "select * from user where user='"+username+"';";
ResultSet rs = st.executeQuery(sql2);
if(rs.next())
{
response.sendRedirect("index.html?err=Username already taken");
}
else
{
String sql = "insert into user values('"+name+"', '"+username+"','"+pass+"',"+cpass+");";
st.executeUpdate(sql);
response.sendRedirect("blank.html");
}
%>
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","");
Statement st = con.createStatement();
String name = request.getParameter("name");
String username = request.getParameter("user");
String pass = request.getParameter("pas");
String cpass = request.getParameter("cpas");
String sql2 = "select * from user where user='"+username+"';";
ResultSet rs = st.executeQuery(sql2);
if(rs != null && rs.next())
{
response.sendRedirect("index.html?err=Username already taken");
}
else
{
String sql = "insert into user values('"+name+"', '"+username+"','"+pass+"',"+cpass+");";
st.executeUpdate(sql);
response.sendRedirect("blank.html");
}
I want this function to display the highest value and the index in the array.If the index is the highest, it will retrieve all the value in sql. But when I run this program, it displays a lot of values...How to solve it?
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0];
System.out.println(highest); // display value in aa[0]
for(int i=1;i<aa.length;i++)
{
if(aa[i]>highest)
{
highest=aa[i];
System.out.println(highest); //print the highest value only
System.out.println(i);
String sql ="Select * from placeseen where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, i+1);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
else if(highest==aa[0])
{
String sql ="Select * from placeseen where ID =1";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
}
Use MAX
Please change your approach, and use the SQL MAX function. Something like,
String sql = "SELECT * FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
You could then use something like
int id = rs.getInt("id");
float budget = rs.getFloat("budget");
And I would recommend limiting the columns (if you only want the two) like
String sql = "SELECT id, budget FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
Why not use a for (int i = 0; i < array.lenght; i++)?
Store array[i] in a variable, and the actual int found in that index in another variable. Then, when you loop through it more: if (array[i] > biggestInt), store the new index number and new biggest integer in their appropriate variables.
I keep getting the following exception: org.apache.jasper.JasperException: java.util.NoSuchElementException
Could you please help me with my code, because i'm clearly missing something. A lot of thanks in advance!
The JSP file:
<%
Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
StringBuffer sb = new StringBuffer(name);
sb.deleteCharAt(0);
VoCo.Vogel.Delete(sb.toString());
}
%>
<br>
<div class="navigator">
Add
<a id="currenttab" href="waarnemingen.jsp">Delete</a>
</div>
<br> <br> <br>
<form action="waarnemingen.jsp" method="post">
<table>
<tr>
<th>Datum</th>
<th>Tijd</th>
<th>Plaats</th>
<th>Spotternaam</th>
<th>Vogelsoort</th>
</tr>
<%
List list = VoCo.Vogel.GetWaarnemingen();
int id = 0;
String box = null;
Iterator<String> it = list.iterator();
while (it.hasNext()) {
id = Integer.parseInt(it.next());
out.print("<tr>");
for (int i = 0; i < 5; i++) {
out.print("<td>");
out.print(it.next());
out.print("</td>");
}
out.print("<td>");
box = "<input name=r" + id + " type='checkbox'>";
out.print(box);
out.print("</td>");
out.print("</tr>");
}
%>
</table>
<br>
<input type="submit" value="Delete">
</form>
The java file:
public class Vogel {
static final String url = "jdbc:mysql://localhost:3306/turving";
public static void Insert(String datum, String tijd, String plaats, String spotternaam, String vogelsoort) {
try {
String insert = "INSERT INTO turving(datum, tijd, plaats, spotternaam, vogelsoort)" + "VALUES (?, ?, ?, ?, ?)";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
PreparedStatement ps = con.prepareStatement(insert);
ps.setString(1, datum);
ps.setString(2, tijd);
ps.setString(3, plaats);
ps.setString(4, spotternaam);
ps.setString(5, vogelsoort);
ps.executeUpdate();
con.close();
} catch (Exception ex) {
Logger.getLogger(Vogel.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static List GetWaarnemingen() {
List<String> list = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM turving");
while(result.next())
{
list.add(result.getString("id"));
list.add(result.getString("datum"));
list.add(result.getString("tijd"));
list.add(result.getString("plaats"));
list.add(result.getString("spotternaam"));
list.add(result.getString("vogelsoort"));
}
con.close();
} catch (Exception ex) {
Logger.getLogger(Vogel.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
public static void Delete(String id) {
try {
String delete = "DELETE from turving WHERE id = ?";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "");
PreparedStatement ps = con.prepareStatement(delete);
ps.setString(1, id);
ps.executeUpdate();
con.close();
} catch (Exception ex) {
Logger.getLogger(Vogel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The problem is here:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
id = Integer.parseInt(it.next());
out.print("<tr>");
for (int i = 0; i < 5; i++) {
out.print("<td>");
out.print(it.next());
out.print("</td>");
}
You're calling it.next() too many times. The first call should be saved in a variable so you don't call it again in the subloop.
It should be like:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = (String)it.next();
id = Integer.parseInt(item);
out.print("<tr>");
for (int i = 0; i < 5; i++) {
out.print("<td>");
out.print(item);
out.print("</td>");
}