I am trying to figure out a way to see if the sql injection is correct based on the user input and if so, delete that row.
For instance the user enters 123 for an idNumber, if that number exits, the the sql statement "select * from student where idNumber = " + idNumber + ";" would be correct.
When it is verified that it is correct, I would then use another statement to delete the query.
My main issue is figuring out how to verify it is correct.
Thanks!
public static void CheckStudent(Connection con, String idNumber) throws SQLException {
Statement stmt = null;
String query = "select * from student where idNumber = " + idNumber + ";"
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (!rs.isBeforeFirst() ) {
//Here is where you do the check
System.out.println("No data");
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
Every time I run this code it gives me an exhauset resultset error. Im not sure what Im doing wrong but Ive tried removing the .next(); code for either one or all resultsets and then the error given is the ResultSet next wasnt called.
Im not sure what Im doing wrong. Just curious what people might think the issue could be? Ive done similar earlier in my servlet code but only used 1 statement and then 1 prepared statement. This time Im using 2 statements and 1 prepared statement.
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
rs11.next();
ResultSet rs12 = stmt.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
rs12.next();
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
int olo1 = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)");
pstmt1.clearParameters();
pstmt1.setInt(1,olo);
pstmt1.setInt(2,olo1);
ResultSet rs1 = pstmt1.executeQuery();
rs1.next();
Some ideas on your code (in comments)
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
//Check if you HAVE a line here!
if(!rs11.next()) {
System.out.println("No Recipe Found");
}
//Use stmt1 - that's why you created it?!
ResultSet rs12 = stmt1.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
if(!rs12.next()) {
System.out.println("No Ingredient Found");
}
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
//Read Ingredient from rs12 -> that's where you selected it into
int olo1 = ((Number) rs12.getObject(1).intValue(); //convert resultset value to int
While this might point you into the right direction for solving the current issue, you should consider learning about clean code.
Consider this code making use of try-with-resource, refactored out some methods, using prepared statements.
//Replace exiting code
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
int recipieId = getRecipeId(con, opt1);
int ingredientId = getIngredientId(con, ingr1);
if(recipeId > 0 && ingredientId > 0) {
//Process result
insertRecLnk(con, recipeId, ingredientId);
} else {
System.out.println("No INSERT");
}
//Helper functions
protected int getRecipeId(Connection con, String rec) {
try(PreparedStatement st = con.prepareStatement("SELECT recipe_ID FROM GM_Recipes WHERE rec_name=?")) {
st.setString(1, rec);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Recipe Found");
return -1;
}
protected int getIngredientId(Connection con, String ing) {
try(PreparedStatement st = con.prepareStatement("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name=?")) {
st.setString(1, ing);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Ingredient Found");
return -1;
}
protected void insertRecLnk(Connection con, int rId, int iId) {
try(PreparedStatement ps = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)")) {
ps.setInt(1, rId);
ps.setInt(2, iId);
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
}
I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}
I am trying to update a table in the database where i m accepting fees from the students and maintaining the record of the amount received, total amount received, and the mode of payment etc.
my code is as follows:
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl,"root","17121990");
System.out.println("connected!");
String firstname=pay_enter_firstname.getText();
String lastname=pay_enter_lastname.getText();
String amt=pay_enter_amt.getText();
int amount=Integer.parseInt(amt);
String day=pay_enter_date.getText();
String cheque_no=pay_enter_chequeno.getText();
String mode=pay_enter_mode.getText();
int totalamount=10000;
int bal_amt=totalamount-amount;
String remark=pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
if(rs.next())
{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
while(rs.next())
{
int temp =rs.getInt(1);
if (temp ==id)
{
int amtrecvd2= rs.getInt(2);
bal_amt=totalamount- (amtrecvd2+amount);
String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
}
}
}
if(!rs.next())
{
String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
Statement stmt1=con.createStatement();
int result=stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
}
catch (ClassNotFoundException | SQLException | NumberFormatException e)
{
e.printStackTrace();
}
}
Initially when i add new values i get it properly but when i am trying to update an existing row i get the error that i m making a duplicate entry for primary key id.
what condition should i check so that i come to know that the result set is not having that particular id value and new person is paying the fee??
This condition:
if(!rs.next())
is being checked outside the while loop. This condition is always true and will try to insert a record even if update has taken place.
To avoid this, i suggest using a flag variable. Once an update has occurred, set the value of this flag to 1.
Check if it has been made 1 instead of if(!rs.next()) and go inside.
You're two if statements are colliding...
// If this is true...
if(rs.next()) {
// ...
// Looping till the it's false...
while(rs.next()) {
// ....
}
}
// Will mean that this is false...
if(!rs.next())
You should be using an else
if(rs.next()) {
// ...
while(rs.next()) {
// ....
}
} else {...}
Updated
After an enlightening conversion with Aashray (thanks), we've concluded that your logic is broken
Rather then manually trying to find the record manually by match the id's let the SQL database do it for you.
Instead of....
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
You should be using...
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);
This will return a ResultSet that is either empty (no matches) or with (hopefully) one row.
From there, calling rs.next() will now let you branch of between an update or insert correctly.
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, "root", "17121990");
System.out.println("connected!");
String firstname = pay_enter_firstname.getText();
String lastname = pay_enter_lastname.getText();
String amt = pay_enter_amt.getText();
int amount = Integer.parseInt(amt);
String day = pay_enter_date.getText();
String cheque_no = pay_enter_chequeno.getText();
String mode = pay_enter_mode.getText();
int totalamount = 10000;
int bal_amt = totalamount - amount;
String remark = pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);
if (rs.next()) {
int amtrecvd2 = rs.getInt(2);
bal_amt = totalamount - (amtrecvd2 + amount);
String updt = "UPDATE payment SET Amountreceivd=" + (amtrecvd2 + amount) + ",lastamtreceived=" + amount + ",dte='" + day + "', balance_amt =" + bal_amt + " WHERE id =" + id + ";";
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
} else {
String str = " INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES (" + id + ",'" + firstname + "','" + lastname + "'," + amount + ",'" + day + "'," + amount + ",'" + mode + "','" + cheque_no + "'," + bal_amt + "," + totalamount + ",'" + remark + "')";
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
} catch (ClassNotFoundException | SQLException | NumberFormatException e) {
e.printStackTrace();
}
}
I think this may help you
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl,"root","17121990");
System.out.println("connected!");
String firstname=pay_enter_firstname.getText();
String lastname=pay_enter_lastname.getText();
String amt=pay_enter_amt.getText();
int amount=Integer.parseInt(amt);
String day=pay_enter_date.getText();
String cheque_no=pay_enter_chequeno.getText();
String mode=pay_enter_mode.getText();
int totalamount=10000;
int bal_amt=totalamount-amount;
String remark=pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
if(rs.next())
{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
while(rs.next())
{
int temp =rs.getInt(1);
if (temp ==id)
{
int amtrecvd2= rs.getInt(2);
bal_amt=totalamount- (amtrecvd2+amount);
String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
}
}
}
else
{
String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
Statement stmt1=con.createStatement();
int result=stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
}
catch (ClassNotFoundException | SQLException | NumberFormatException e)
{
e.printStackTrace();
}
Hi guys can u tell me what is wrong with my code?
When I set my ResultSet as "SELECT * FROM Table1" it works perfectly,
also if it is "SELECT key, itemName, itemPrice, itemQuantity FROM Table1"
but when I try to use only one of them or two it prints out an error column not found.
My database is stored in MS Acceess. That's my main:
try (Connection cn = DBUtil.getConnection(DBType.MS_ACCESS);
Statement st = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT Table1.key FROM Table1");) {
Table1.displayData(rs);
} catch (SQLException ex) {
DBUtil.processException(ex);
}
and that's Table1.java:
public class Table1 {
public static void displayData(ResultSet rs) throws SQLException {
// to print out my database
while (rs.next()) {
StringBuffer buffer = new StringBuffer();
buffer.append(rs.getString("key") + " ");
buffer.append(rs.getString("itemName") + " ");
double price = rs.getDouble("itemPrice");
DecimalFormat pounds = new DecimalFormat("£#,##0.00");
String formattedPrice = pounds.format(price);
buffer.append(formattedPrice + " ");
buffer.append(rs.getInt("itemQuantity") + " ");
System.out.println(buffer.toString());
}
}
}
Your result set will only contain the columns that you define in your select query. So if you do
rs.getString("itemName")
then you have to select that column in your query, which you don't
st.executeQuery("SELECT Table1.key FROM Table1")
^-----------------column missing
Do
st.executeQuery("select key, itemName, itemPrice, itemQuantity from Table1")
you should use
buffer.append(rs.getString("Table1.key") + " ");
resultset have the data with name which you have given in select query.(key=Table1.key)