jsp control server side on form - java

I want compare to the data sent with all data in the db. this coce compare the date insert only with the last row. how can I compare with all row in the db?
................................................................................................
String sData= request.getParameter("idatadata");
String sAzienda= request.getParameter("idazienda");
String sCommessa= request.getParameter("idcommessa");
String date = "";
String company = "";
String order = "";
Connect con = new Connect();
try {
Connection connection = con.createConnection();
Statement statement = connection.createStatement();
String sql ="SELECT * FROM table";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()) {
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
}
if((sData.equals(date) && sAzienda.equals(company)) && sCommessa.equals(order)) {
out.print("already sent");
con.closeConnection(connection);
}
else {
DbConnect.insertInDb(connection, sData, sOre, sMinuti, sAzienda, sCommessa, sRifInterno);
dbc.closeConnection(connection);
response.getWriter().append("ok! ");
}
} catch (Exception e) {
e.printStackTrace();
}
}

The reason why you are checking only the last row, is that your while loop keeps overwriting your local variables each time you retrieve a row:
while(resultSet.next()) {
// these lines overwrite the local vars for each row
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
}
But you don't actually check the local vars inside the loop before moving on to the next row from the db. You should add the check into the loop:
while(resultSet.next()) {
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
// add your check here
if((sData.equals(date) && sAzienda.equals(company)) && sCommessa.equals(order)) {
out.print("already sent");
break;
}
}
Preferably, just perform a select based on the data you are looking for. If you get no results, then the data isn't in the db. This method is much more efficient. If you do decide to go down this path (which is a good idea), use a prepared statement so that you don't introduce a SQL injection vulnerability into your code.

Related

JSP won't display string return value

I have a class called "Database" that is working perfectly well. It queries a database and returns the results as a string. When I call the class from my "Test" class it returns the results string and I can print it with System.out.println().
I'm trying to use this class on a JSP page using the same two lines of code to instantiate the class and get the string output. When I try to output on the JSP page I get nothing. What am I doing wrong? I'm completely stumped.
Class Code:
public class Database {
static String[][] reservations = new String[7][20];
public Database (String theDate) {
String url = "jdbc:mysql://myurl.com:3306/";
String driver = "com.mysql.cj.jdbc.Driver";
String user = "myusername";
String pass = "mypassword";
String db = "class";
String options = "?useSSL=false";
try (Connection conn = DriverManager.getConnection(url + db + options, user, pass);
Statement statement = conn.createStatement()) {
String query = "select reservation.first, reservation.last, startday, numberofdays, guides.first as guidefirst, guides.last as guidelast, locations.location from reservation left join guides on reservation.guide = idguides left join locations on reservation.location = idlocations where StartDay >= " + theDate;
ResultSet rs = statement.executeQuery(query);
int row = 0;
while (rs.next()) {
reservations[0][row] = rs.getString("first");
reservations[1][row] = rs.getString("last");
row++;
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public String getStringRes () {
String returnString = "";
for(int i=0; i<20; i++) {
if (reservations[0][i] != null) {
returnString += i + " " + reservations[0][i];
returnString += " " + reservations[1][i] + "\n";
}
}
return returnString;
} }
JSP Code:
<%# page import="mypackage.Database" %>
<%
Database db = new Database("2015-07-01");
String str = db.getStringRes();
%>
<%= str %>
Your code contains 3 mistakes.
The most problematic
} catch (SQLException e) {
e.printStackTrace();
}
Don't ever do that. Go into your IDE settings and eliminate this template. It should be throw new RuntimeException("Unhandled", e); instead.
Here's what happened: Your SQL statement is erroneous (in two ways, even). This causes an exception. Your code handles this by ignoring it (it's printed, but, your code finishes normally). Hence, the string result remains blank (because it starts out that way and the code that is supposed to give it its real value never ran, due to the exception that you ignored).
Your SQL is broken.
The actual explanation is that date literals need to be in quotes, in SQL. Yours is not.
But that's not how you pass parameters into SQL.
The bigger issue is that passing any value like this into an SQL means your machine will be hacked in a matter of days. That's called 'SQL injection'. You don't want it. The solution is preparedstatements, where you let the JDBC driver and/or the database take care of escaping or otherwise passing string data without the SQL db engine trying to interpret it as SQL (Because, obviously, letting arbitrary users type stuff in that your DB engine then treats as SQL means you're just waiting for someone to construct some SQL such that your db engine ends up executing DROP TABLE reservation CASCADE; EXECUTE 'FORMAT C: /Y'; --.
Minor style nit
Doing business logic in constructors is a bad idea. The query should be done from getStringRes, most likely. That's also a bit of a crazy method name. Not very informative.
Which gets us to...
try (Connection conn = DriverManager.getConnection(url + db + options, user, pass);
PreparedStatement statement = conn.prepareStatement("SELECT reservation.first, .... FROM .... WHERE StartDay >= ?")) {
statement.setString(1, theDate);
try (ResultSet rs = statement.executeQuery()) {
...
}
} catch (SQLException e) {
throw new RuntimeException("unhandled", e);
}

java load values from database into comboBox

Hi my aim is to load combobox with vaules from a database the code below works fine with one issue i get two of the first item so what must i do to prevent this
public void loadCombos() {
try {
try {
String cs = "jdbc:mysql://localhost:3307/booksalvation6";
String user = "root";
String password = "letmein";
jComboBox2.removeAllItems();// make sure old data gone
PreparedStatement pstpost;
ResultSet rspost;
conCombos = DriverManager.getConnection(cs, user, password);
for (int i = 1; i < 11; i++) {
String querypost = "select * from post "
+ "WHERE postage_id =" + i;
// load postage selections
pstpost = conCombos.prepareStatement(querypost);
rspost = pstpost.executeQuery();
while (rspost.next()) {
String Mypost = rspost.getString(6);
jComboBox2.addItem(Mypost);
}
}
} catch (SQLException ex) {
Logger.getLogger(BasicFrame.class.getName()).log(Level.SEVERE, null, ex);
}
conCombos.close();
} catch (SQLException ex) {
Logger.getLogger(BasicFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
You are using PreparedStatement but not in proper way.
Since you are looking only for one column to fetch all the column values which have postage_id between 1 to 10.
You can achieve it in single query:
select unique(combo_value_column_name) from post
where postage_id>=? and postage_id<=?
set the parameter via calling PreparedStatement#setInt(index,value) set it 1 and 10.
Just fetch single column and only unique values.
It's better explained under Java Tutorial on Using Prepared Statements
Instead of calling JComboBox#addItem() first prepare the whole list then finally set it once.
Read more...
Final Note: Follow Java Naming Convention.

Resultset error

Im working with Java EE and derby, i try to get data from my resultset and put them in int and string but don't work it gives me this error :
java.sql.SQLException: Invalid operation for the current cursor location.
i tryed result.next() but nothing, here is my code :
Connection conn = null;
Statement stmt = null;
ResultSet result = null;
Hotel hot = new Hotel();
try {
synchronized (dataSource) {
conn = dataSource.getConnection();
}
stmt = conn.createStatement();
String req = "SELECT * FROM hotel WHERE num = " + num;
result = stmt.executeQuery(req);
}
//result.next();
int xxnum = result.getInt(1);
String nom = result.getString("nom");
String villeV = result.getString("ville");
int etoilesV = result.getInt("etoiles");
String directeur = result.getString("directeur");
Hotel hol = new Hotel(num, nom, villeV, etoilesV, directeur);
result.close();
stmt.close();
return hol;
} catch (SQLException ex) {
throw new DAOException("probl�me r�cup�ration de la liste des hotels !!", ex);
} finally {
closeConnection(conn);
}
The error
java.sql.SQLException: Invalid operation for the current cursor location.
will be caused by not setting the cursor to the next position using
result.next();
Place the call in an if statement
if (result.next()) {
// build Hotel object
...
}
If you still don't see any results, run your SQL directly against your database and see if any records are returned. If not, adjust your query or data accordingly.
Side Notes:
Use PreparedStatement to protect against SQL Injection attacks.
Place result.close(); and stmt.close(); calls in a finally block.
You need to use next() method of ResultSet.
Check the Javadocs here and I have snipped the relevant part below.
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
So you need to do this in your code:
if(result.next())
{
int xxnum = result.getInt(1);
String nom = result.getString("nom");
String villeV = result.getString("ville");
int etoilesV = result.getInt("etoiles");
String directeur = result.getString("directeur");
}

compare integer text field value with mysql data in java

I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}

java:After entering id whole information should display

I have created one form, which contain information of user like name, contact no, photo id number, job profile etc. Once he enter all the information, it will store in database. When he login for second time, after entering photo id number whole information should display on the form, without he enters. I am using key typed event for this. I have tried this code, but it is throwing exception as
java.sql.SQLException: Before start of result set
public void show()
{
try
{
String id=photo_id_num.getText();
System.out.println(""+id);
Connect c=new Connect();
con=c.getConnection();
Statement stmt=con.createStatement();
String queryPhotoid = "select * from tbl_visitor ";
ResultSet rs1= stmt.executeQuery(queryPhotoid);
while (rs1.next())
{
if(id.equals(rs1.getString(6)))
{
// Read values using column name
String name = rs1.getString(2);
int contno = rs1.getInt(3);
String orgname = rs1.getString(4);
String jobpro = rs1.getString(5);
String category = rs1.getString(7);
String date = rs1.getString(8);
int noofpeople = rs1.getInt(9);
Blob image = rs1.getBlob(10);
int extrapeople = rs1.getInt(11);
System.out.println("Name:"+name+" Contact_no:"+contno+"Org_Name:"+orgname+" Job_profile:"+jobpro+"Category:"+category+"Date:"+date+"No_Of_People:"+noofpeople+"image:"+image+"Having extra people:"+extrapeople);
}
}
}
catch (SQLException sqlEx)
{
sqlEx.printStackTrace();
}
}
When you fetch result set the cursor is prior to the first record so you need to take cursor to the first record by executing resultSet.next(), Here in your case you are reading before positioning the cursor
System.out.println("ranu"+rs1.getString(6));
while (rs1.next());
So you first need to do rs.next() then only you can read the records
So make it as follows
ResultSet rs1= stmt.executeQuery(queryPhotoid);
while (rs1.next()) {
System.out.println("ranu"+rs1.getString(6));
if(id.equals(rs1.getString(6)))
{
// blah blah..
}
//blah
}

Categories