NoSuchElementException in JSP with MYSQL - java

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>");
}

Related

JAVA:How to update/refresh Table after changes made into database

I'm new to java and DBMS. I'm trying to update/refresh the JTable after any changes made into the H2 database when user clicks a same button to show JTable and after writing data into database(when write button is clicked). I tried some methods and read some posts but couldn't find anything essential to my program. The code below illustrates my problem.
This is the method used to read from database and show it on JTable
public void readActiveData() throws IOException, InstantiationException, IllegalAccessException, SQLException {
try {
st = conn.createStatement();
} catch (SQLException sqlex) {
JOptionPane.showMessageDialog(null, "Can't connect to DB. " + sqlex);
dispose();
}
try {
rs = st.executeQuery("SELECT * FROM main_data WHERE expirationDate > NOW() + 1;");
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt(1);
String ovogNer = rs.getString(2);
String regNum = rs.getString(3);
String itemName = rs.getString(4);
String note = rs.getString(5);
int zHemjee = rs.getInt(6);
int hvv = rs.getInt(7);
int hugatsaa = rs.getInt(8);
today = rs.getDate(9);
int totalPay = rs.getInt(10);
expirationDate = rs.getDate(11);
rows++;
}
regData = new Object[rows][11];
Object[] Colheads = {"Бүртгэлийн дугаар", "Овог нэр", "Регистрийн дугаар", "Барьцаа",
"Тэмдэглэл", "Зээлийн хэмжээ", "Хүү (%)", "Хугацаа", "Огноо", "Нийт төлөх", "Дуусах хугацаа"};
rs = st.executeQuery("SELECT * FROM main_data WHERE expirationDate > NOW() + 1;");
for (int i1 = 0; i1 < rows; i1++) {
rs.next();
for (int j1 = 0; j1 < 11; j1++) {
regData[i1][j1] = rs.getString(j1 + 1);
}
}
model = new DefaultTableModel(regData, Colheads);
table = new JTable(model);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
activeDataPanel.add(jsp);
rs.close();
st.close();
conn.close();
}
And this is the method i'm using to write data into the database
public void writeDataIntoDB() throws InstantiationException, IllegalAccessException {
ResultSet rs = null;
Connection conn = null;
Statement st = null;
PreparedStatement pst = null;
final String URL = "jdbc:h2:~/registDB";
final String USER = "admin";
final String PASS = "password";
LocalDate currentDate = LocalDate.now();
String input = hugatsaaFld.getText();
long addDays = Long.parseLong(input);
expiration = currentDate.plusDays(addDays);
expirationDate = java.sql.Date.valueOf(expiration);
try {
Class.forName("org.h2.Driver").newInstance();
conn = DriverManager.getConnection(URL, USER, PASS);
String sql = "INSERT INTO main_data(ovogNer,regNum,itemName,note,zHemjee,hvv,hugatsaa,date,totalPay,expirationDate)"
+ "VALUES"
+ "(?,?,?,?,?,?,?,?,?,? )";
pst = conn.prepareStatement(sql);
pst.setString(1, getOvogNer());
pst.setString(2, getRegNum());
pst.setString(3, getItemName());
pst.setString(4, getNote());
pst.setInt(5, +getzHemjee());
pst.setInt(6, +getHvv());
pst.setLong(7, +getHugatsaa());
pst.setDate(8, java.sql.Date.valueOf(LocalDate.now()));
pst.setDouble(9, getTotalPay());
pst.setDate(10, expirationDate);
pst.executeUpdate();
pst.close();
conn.close();
} catch (SQLException se) {
JOptionPane.showMessageDialog(null, "Error: " + se);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
This question has been answered here
but it comes down to clearing and rerendering your JTable object. i.e. refresh, the post above explains it quite nicely.
Hope you get it right.

Create dropdown box based on database query?

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.

show same row value When run the program in java

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.

How to Store Array value in table column in mySql using java

hello i am trying to retrieve data in two result set. then i have store in both resultset to String Array, after this process i have to store my String array to another table how to so this kindly tell me..
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.
getConnection("jdbc:mysql://localhost:3306/lportal", "root", "ubuntu123");
PreparedStatement stmt = (PreparedStatement) con.
prepareStatement("SELECT * FROM Testi_Testimonial where subject = ?");
stmt.setString(1, search);
stmt.execute();
rs = (ResultSet) stmt.getResultSet();
while (rs.next()) {
anArray[i] = rs.getString("subject");
System.out.println(anArray[i]);
i++;
count++;
}
PreparedStatement stmt1 = (PreparedStatement) con.
prepareStatement("SELECT * FROM Testi_Testimonial where subject != ?");
stmt1.setString(1, search);
stmt1.execute();
rs1 = (ResultSet) stmt1.getResultSet();
while (rs1.next()) {
anArray[i] = rs1.getString("subject");
System.out.println(anArray[i]);
i++;
count++;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("problem in connection");
}
Please tell me how should I store my array to Temp table? my "Temp" table has column subject I want to store myArray to subject column... kindly tell me how to do this.
try this after getting resultset in rs:
PreparedStatement st = (PreparedStatement) con.prepareStatement("insert into temp values(?)");
i=0;
while(rs.next())
{
st.setString(1,anArray[i]);
st.executeUpdate();
i++;
}
You just iterate the arrayList. You got the subject List as respective.
public class TestArrayList {
public static void main(String[] args) {
/*create two arrayList*/
List<String> tempOneList = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay", "root", "root");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM subjecttable");
while (res.next()) {
tempOneList.add(res.getString("subject"));
}
ResultSet resOne = st.executeQuery("SELECT * FROM subjecttabletwo");
while (resOne.next()) {
tempOneList.add(resOne.getString("subject"));
}
System.out.println("temp/List>>--" + tempOneList.size());
for(int i=0;i<tempOneList.size();i++){
System.out.println(tempOneList.get(i));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("problem in connection");
}
}
}
PreparedStatement ps =
(PreparedStatement) con.prepareStatement("insert into temp values(?)");
j=0;
while(rs.next())
{
ps.setString(1,anArray[j]);
ps.executeUpdate();
j++;
}

converting list to string and then return

i want to get the list generated in the following code as string before return from the function "LookUpTransaction". what should i do.?
public String[] LookUpTransaction() {
List list=new ArrayList();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bank", "root", "root");
PreparedStatement ps = con
.prepareStatement("select accountno,details,amount from transaction");
rs = ps.executeQuery();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getString(2));
list.add(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}
String[] strarray = new String[list.size()];
return list.toArray(strarray);
}
You could use return Arrays.toString(strarray); In this case you have to change the return type of your method to String. That is your code must be modified as shown below:
public String LookUpTransaction() {
List list=new ArrayList();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bank", "root", "root");
PreparedStatement ps = con
.prepareStatement("select accountno,details,amount from transaction");
rs = ps.executeQuery();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getString(2));
list.add(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}
String[] strarray = new String[list.size()];
strarray = list.toArray(strarray);
return Arrays.toString(strarray);
}
Please note that the Arrays.toString(strarray) returns a string representation of the contents of the specified array (strarray in your scenario). The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). If you are looking to iterate over the list & concatenating the elements you could try something like this:
public String LookUpTransaction() {
List list=new ArrayList();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bank", "root", "root");
PreparedStatement ps = con
.prepareStatement("select accountno,details,amount from transaction");
rs = ps.executeQuery();
while(rs.next()){
list.add(rs.getString(1));
list.add(rs.getString(2));
list.add(rs.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder stringBuilder = new StringBuilder();
for (String str : list) {
stringBuilder.append(str);
}
return stringBuilder.toString();
}
Use List.toArray(), followed by Arrays.toString()
String[] y = x.toArray(new String[0]);
Arrays.toString(y)

Categories