Cause of parameter index out of range for code sample - java

Why am I getting "parameter index out of range (1>no. of parameters,which is 0)" for the code below?
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
String tabId = lblTableId.getText().trim();
try {
DBConnection db = new DBConnection();
Connection con = db.getConnectionMyWareHouse(Main.dwh.lblSessionWarehouse.getText());
String query1 = "Select DWTableId,DWTableName from datawarehousetable where DWTableId=? and DWTableName=? ";
System.out.println("OG Query ---->"+query1);
PreparedStatement ps1 = con.prepareStatement(query1);
ps1.setString(1, tabId);
ResultSet rs1 = ps1.executeQuery();
String strTN = "";
if(rs1.next())
{
strTN = rs1.getString("DWTableName");
}
String query2 = "Delete from datawarehousetable where DWTableId= ?";
System.out.println("OG Query ---->"+query2);
PreparedStatement ps2 = con.prepareStatement(query2);
ps2.setString(1, tabId);
int rs2 = ps2.executeUpdate();
String query3 = "Drop table " + strTN;
System.out.println("OG Query ---->"+query3);
PreparedStatement ps3 = con.prepareStatement(query3);
ps3.setString(1, tabId);
int rs3 = ps3.executeUpdate();
JOptionPane.showMessageDialog(null, "Table deleted successfully.", "Successful", JOptionPane.INFORMATION_MESSAGE);
con.close();
}
catch(Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error : " + e.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
}
}

Related

Verify if the row is not available in mySQL table

I want message (the row is not available in the stock) if row is not available in the database. I try the following code but the error....!
//Code
try {
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int count = 0;
while (rs.next()){
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Item is available in Stock"
} else {
JOptionPane.showMessageDialog(null, "ID:" + txtS.getText() + "is not available in the Stock please update the Stock");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
// error....
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
.....
.....
....
....
Please help.....
You are not setting the value for the ? in your SELECT statement.
Given that it's an ID I will assume it is an int.
You need:
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, value);
ResultSet rs = ps.executeQuery();
EDIT
Try changing your methodology to this:
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, value);
ResultSet rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Item is available in Stock"
}
else {
JOptionPane.showMessageDialog(null, "ID:" + txtS.getText() + "is not available in the Stock please update the Stock");
}
Thanks # Matt for help
i got a perfect Answer by using this code......
try {
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, txtS.getText());
ResultSet rs = ps.executeQuery();
int count = 0;
while (rs.next()){
// code update here
count = rs.getInt(1);
// count = count + 1;
}
if (count == 1) {

Exhausted ResultSet Issue with Servlet Oracle

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

How to dump resultset data into a database table

I am creating a resultset through an SQL query ('SELECT_PROCESS_INITIAL_REQUEST') which basically just grabs everything out of an SQL database table.
Statement stmt = conn.createStatement();
String sql = SQLDataAdaptor.SELECT_PROCESS_INITIAL_REQUEST;
ResultSet rsRequest = stmt.executeQuery(sql);
I then want to dump that data into an identical table to the original but in a different database. How would I do that?
Dumping it in another database means that Java will have to handle your resultset. So i'm afraid you have to do this programmatically.
Think of "prepared statements", "add batch method" and don't forget to execute your inserts every n records.
Using the example on Java Tutorial Website-
public static void viewTable(Connection con, String dbName)
throws SQLException {
//Modify this code according to 2nd database vendor and credentials-
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn2 = DriverManager.getConnection(url);
Statement stmt = null;
Statement insertStmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, " +
"SALES, TOTAL " +
"from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
insertStmt = conn2.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
String insertQuery = "INSERT INTO COFFEES (COF_NAME, SUP_ID, PRICE, sales, total) VALUES (coffeeName,supplierID, proce, sales, total);
try{
insertStmt.execute(insertQuery);
}catch(SQLExeption e){
e.printStackTrace();
}
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) { stmt.close();}
if(insertStmt != null) {insertStmt.close();}
}
}

adding the values from gui to the database table

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

Exception - java.sql.SQLException: Operation not allowed after ResultSet closed

I am getting an exception like as
java.sql.SQLException: Before start of result set when calling getInt() method
My code is as follows:::
public void setdateTOSource(){
try{
String q = "SELECT * FROM ipp.resource;";
ResultSet result = DB_Access.getData(q);
System.out.println("Size result set"+result.getFetchSize());
while(result.next()){
getIpSource().add(result.getString(1));
System.out.println(result.getString(1));
}
System.out.println("source size "+getIpSource().size());
}
catch(Exception e){
System.out.println(e);
}
}
public void insertTargetToDb(List<String> targetValue){
try{
Connection con = DB_Connect.getDataBaseConnection();
Statement statement1 = con.createStatement();
int val=0;
String q1 = "SELECT MAX(area_id) as aa FROM ipp.area;";
ResultSet resultset = statement1.executeQuery(q1);
if(resultset.next()){
val = resultset.getInt(1);
};
val++;
String q2 = "INSERT INTO ipp.area VALUES("+val+",'"+getAreaName()+"',1);";
Statement statement2 = con.createStatement();
statement1.executeUpdate(q2);
for( int y=0;y<targetValue.size();y++){
System.out.println("FS");
String ip=targetValue.get(y);
System.out.println("ip" +ip);
String q3 ="SELECT resource_id FROM ipp.resource r where ip_address like '"+ip+"%';";
Statement statement3 = con.createStatement();
ResultSet resultset3 =statement3.executeQuery(q3);
System.out.println("FS1");
// ResultSet result1 =DB_Access.getData(q3);
System.out.println("FS2");
System.out.println("result set"+resultset3.getFetchSize());
//====================================================================
while(resultset3.next()){
setId(resultset.getInt(1));
}
System.out.println("result :........."+resultset3.getInt("resource_id"));
System.out.println("FS3");
String q4 = "INSERT INTO ipp.used_resource VALUES("+val+","+getId()+");";
Statement statement4= con.createStatement();
statement4.executeUpdate(q4);
// DB_Access.setData(q3);
statement3.close();
statement4.close();
// resultset3.close();
}
resultset.close();
statement1.close();
statement2.close();
con.close();
addMessage("Area created Successfully");
}
catch(Exception e){
System.out.println(e);
}
}
Exception comes after line
//==========================
resource_id is an integer value
This line
while(resultset3.next()){
setId(resultset.getInt(1));
}
must be replaced with?
while(resultset3.next()){
setId(resultset3.getInt(1));
}

Categories