org.postgresql.util.PSQLException: No value specified for parameter 1 - java

The query runs perfectly fine when directly executed in database but it gives me above error..I Have gone through similar questions but couldnt find any sol..
My Dao code
public String BASshiftingStudentsUpdate(HttpServletRequest request)
{
String sql="",msg="";
String[] checkedApps = request.getParameter("checkedApps") != null&& request.getParameter("checkedApps")!=""?request.getParameter("checkedApps").split("\\,") : null;
String ac_year=request.getParameter("acyear");
try
{
if (checkedApps != null)
{
for (int i = 0; i < checkedApps.length; i++)
{
sql=" insert into pmss_school_students_details(admission_no,student_name,parent_name,native_dist,native_mandal,address,caste_code,subcaste_code,admission_year,"
+ "admission_dt,admission_class,present_class,student_photo,entered_by,entered_dt,stu_subcaste_new,mobilenumber,parent_proffession,annual_income,date_of_birth,"
+ "pre_quarterly_marks,pre_annual_marks,achievements,health_problems,height,weight,blood_group,fresh_renewal,identification_marks,orphan,semi_orphan,"
+ "rescued_child,victim,handycapped,school_code,class_promoted,dept_code,dist_office_code,applied_date,stu_id,status,pre_halfyearly_marks,ac_year,"
+ "pre_quarterly_marks_max,pre_halfyearly_marks_max,pre_annual_marks_max,gender,boaders,from_school) "
+ " select admission_no,student_name,parent_name,native_dist,"
+ "native_mandal,address,caste_code,subcaste_code,admission_year,admission_dt,admission_class,present_class+1 as present_class,student_photo,entered_by,entered_dt,"
+ "stu_subcaste_new,mobilenumber,parent_proffession,annual_income,date_of_birth,pre_quarterly_marks,pre_annual_marks,achievements,health_problems,"
+ "height,weight,blood_group,'R' as fresh_renewal,identification_marks,orphan,semi_orphan,rescued_child,victim,handycapped,'"+request.getParameter("to_schools_selected")+"' as school_code,class_promoted,"
+ "dept_code,dist_office_code,applied_date,(substring(stu_id,1,4))::int+1||substr(stu_id,5) as stu_id,'3' as status,pre_halfyearly_marks,(substring(stu_id,1,4))::int+1||'-'||(substring(stu_id,3,2))::int+2 as ac_year,pre_quarterly_marks_max,"
+ "pre_halfyearly_marks_max,pre_annual_marks_max,gender,boaders,school_code from pmss_school_students_details "
+ " where stu_id='"+checkedApps[i]+ "' and school_code='"+ Integer.parseInt(request.getParameter("schoolcode").trim())
+ "' and ac_year=int4(substring('"+ac_year+"',1,4))-1||'-'||int4(substring('"+ac_year+"',6,2))-1";
gen.executeUpdate(sql);
}
}
executeUpdate Method
public int executeUpdate(String sql)
{
Session session = sessionfactory.openSession();
SQLQuery query=null;
int result=0;
try
{
result=session.createSQLQuery(sql).executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (session.isOpen())
{
session.close();
}
}
return result;
}
The columns in query are same in number.

The colon (:) is a prefix for named parameters in Hibernate. Make sure you escape them, e.g. \:\:int+1.

Related

SQL executeUpdate() seems to commit data, but that is not the case. How can I find my error?

I curently work on few SQL queries (MSSQL 2O14), but only "SELECT" query works with executeQuery().
I had use execute() and executeUpdate() on "INSERT INTO" and "UPDATE" queries, but whereas it looks like working, no way.
FYI, in "UPDATE_PREVIOUS_H_LOT_STATUT,
int count= p.executeUpdate(); return 1. If h_lot_number is an unknown lot number, count = 0.
So, if I use wrong data in input, my query isn't executed(Until here, I agree) but when I use the expected data, the query is executed but there is no change in my DB.
How can I find where my error is ?
UPDATE Function :
public static boolean UPDATE_PREVIOUS_H_LOT_STATUT(String h_lot_number_old) {
try {
setUpConnexion("mainDB");
String baseQuery = "UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'";
//PreparedStatement p = newTransact("UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'", "mainDB");
PreparedStatement toReturn = (PreparedStatement) mainCon.prepareStatement(baseQuery);
int count = toReturn.executeUpdate();
if (count > 0) {
Log.d("Sucess : ", "Previous h_lot updated.");
closeCons();
return true;
} else {
Log.e("Error : ", "No lot found with this number.");
closeCons();
return false;
}
} catch (SQLException e) {
error = e.getMessage();
Log.e("Error :", error);
closeCons();
return false;
}
}
LOAD PREVIOUS NUMBER FUNCTION (works perfectly)
public static String LOAD_PREVIOUS_H_LOT_NUMBER(String machineNumber) {
String s = "";
try {
setUpConnexion("mainDB");
ResultSet RS = executeQuery("SELECT h_lot_number FROM valve_assembly_h WHERE machine_number = '" + machineNumber + "' AND statut = 'Actif'", "mainDB");
while (RS.next()) {
s = RS.getString(1);
Log.d("Success : ", "Lot number : " + s);
}
closeResultSet(RS);
} catch (Exception e) {
error = e.getMessage();
Log.e("Error :", error);
s = error;
}
closeCons();
return s;
}
Set up connection function : (works perfectly)
public static boolean setUpConnexion(String DBNAME) {
StrictMode.ThreadPolicy policy;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String connectURL;
try {
CONNECTION MS SQL SERVER
}
return true;
} catch (Exception e) {
System.out.println("SQL ERROR: " + e.getMessage());
e.printStackTrace();
return false;
}
}
Try to commit the transaction manually through the Connection object ,hope it helps.

How to extract specific information from the selected item in a JComboBox?

I have a form that has a ComboBox which it gets its items from a database. The combobox takes numerous column-items from a table inside the database.
I want to take only one of these items (from the combobox) and copy it to a JTextField.
Here's the code of the creation of the ComboBox in the Order.java file:
cbinv = new JComboBox<>();
cbinv.setModel(new InvComboModel(con));
and the code from the InvComboModel.java:
public InvComboModel(Connection con) {
try {
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String query = "SELECT * FROM inventory";
rs = stmt.executeQuery(query);
} catch (SQLException e) {
System.out.println("InvComboModel: " + e.getMessage());
}
}
#Override
public String getElementAt(int index) {
String lstn = null;
try {
rs.absolute(index + 1);
lstn = rs.getString("category") + ", " + rs.getString("description") + ", "
+ rs.getInt("price") + ", " + rs.getInt("quantity");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return lstn;
}
#Override
public int getSize() {
int cnt = 0;
try {
rs.last();
cnt = rs.getRow();
} catch (SQLException ex) {
System.out.println("getSize(): " + ex.getMessage());
}
return cnt;
}
public int getIdInvAt(int index) {
int idInv = 0;
try {
rs.absolute(index + 1);
idInv = rs.getInt("idinv");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return idInv;
}
So, I want when I select something on the Inventory Item to take the third value (which in this case is 500, example image) and copy it to the JTextField of the ItemPrice.
[example][1]: https://i.stack.imgur.com/BWQVw.jpg
In the Order.java file I have the following command but it copies all the selected item in the combobox:
tip.setText((String) cbinv.getSelectedItem());
and when I use the following command it takes the whole line again. It seems that I can't use any other method from the InvComboModel.java file
tip.setText((String) cbinv.getModel().getElementAt());
Thanks in advance.

How to only execute database updates at the end of a while cycle

How can I only make my application execute the changes to a database at the end of the while cycle?
I have this rollback method but I only the changes to be made to the database at the end of it because of inconsistent data handling
I have tried to set auto commit to false but even though the exception was thrown at the second iteration of the while cycle, the changes were still in the database(until the point before the interruption, the tables after that didn't suffer changes).
Am I doing something wrong?
#Override
public void rollback(Database database) throws CustomChangeException {
JdbcConnection connection = (JdbcConnection) database.getConnection();
try {
connection.setAutoCommit(false);
ResultSet rs = getTables(connection);
//if the user chose to use a suffix
if (this.getSuffix() != null) {
while (rs.next()) {
String tableName = rs.getString(3);
if (tableName.endsWith(this.getSuffix())) {
if (!checkColumnsExists(connection, tableName, newName)) {
throw new CustomChangeException("The column " + newName + " doesn't exist in the table " + tableName + " anymore.Please fix this");
}
PreparedStatement s = connection.prepareStatement(getRollbackQuery(tableName));
s.executeUpdate();
logger.info("Column name reversed to " + this.getColumnName() + " in table" + tableName);
}
}
}
//if the user chose to use a regex
if (this.getRegex() != null) {
Pattern pattern = Pattern.compile(this.getRegex());
while (rs.next()) {
String tableName = rs.getString(3);
Matcher matcher = pattern.matcher(tableName);
boolean matches = matcher.matches();
if (matches) {
if (!checkColumnsExists(connection, tableName, newName)) {
logger.error("The column " + newName + " doesn't exist in the table " + tableName + " anymore.Please fix this");
throw new CustomChangeException();
}
PreparedStatement s = connection.prepareStatement(getRollbackQuery(tableName));
s.executeUpdate();
logger.info("Column name reversed to " + this.getColumnName() + " in table" + tableName);
}
}
}
connection.commit();
} catch (SQLException | DatabaseException | DifferentDataTypeException e) {
logger.error(e.getMessage());
throw new CustomChangeException();
}
}

How to set properly an object attribute using reflection in Java?

Database ResultSet example
fclass,geometry,scenario
""elementary_school"","MULTIPOINT(303400.907447057 9044592.97070337)",66
""elementary_school"","MULTIPOINT(302777.056751395 9044333.43169871)",66
""elementary_school"","MULTIPOINT(304182.88271353 9042435.93276122)",66
""elementary_school"","MULTIPOINT(304592.928219703 9041564.59729198)",66
""elementary_school"","MULTIPOINT(311385.417245523 9052785.71100888)",66
""worship"","MULTIPOINT(307397.04764638 9039421.31774996)",66
""worship"","MULTIPOINT(304384.660908793 9047145.34109501)",66
""worship"","MULTIPOINT(304518.616783947 9039859.48619132)",66
""worship"","MULTIPOINT(304689.11878157 9041491.61685193)",66
""worship"","MULTIPOINT(304711.539434326 9047763.53595371)",66
""worship"","MULTIPOINT(303420.353637529 9048419.36252138)",66
Class to be accessed using reflection
public class Amenities {
public Integer amenities_id;
public Integer scenario;
public String fclass;
public String location;
public String buffer;
public TableInfo[] amenity_info;
}
Using reflection
private PostStatus getAmenities(String layerUP, String layer, String[] tableUP, String[] table, String scenarioId) {
PostStatus postStatus=new PostStatus();
String values = "";
for (int i = 0; i < tableUP.length; i++) {
if (tableUP[i].equals("location")) {
//values += "st_astext("+table[i]+")";
values += "st_astext("+table[i]+") as "+table[i];
} else if (tableUP[i].equals("scenario")) {
values += scenarioId+" as scenario";
} else {
values = "property_json->'" + table[i] + "' as "+ table[i] ;
}
if (i < tableUP.length - 1) {
values += ",";
} else {
values = values.replaceAll(",$", "");
}
}
String errorMsg = "";
String query ="";
try (
Connection connection = DriverManager.getConnection(
upURL,
upUser,
upPassword)) {
Statement statement = connection.createStatement();
query="select " + values + " from user_layer\n"
+ "inner join user_layer_data on user_layer.id = user_layer_data.user_layer_id\n"
+ "where user_layer.id=" + layer;
ResultSet data = statement.executeQuery(query);
ArrayList<Amenities> data_in = new ArrayList<>();
while (data.next()) {
Object o = new Amenities();
Class<?> c = o.getClass();
for (int i = 0; i < tableUP.length; i++) {
try {
Field f = c.getDeclaredField(tableUP[i]);
f.setAccessible(true);
if (!tableUP[i].equals("scenario") || !tableUP[i].equals("amenities_id")) {
f.set(o, data.getString(table[i]));
} else if (tableUP[i].equals("scenario")) {
Integer scen=(Integer)data.getInt(tableUP[i]);
f.set(o,scen );
} else if (tableUP[i].equals("location")) {
f.set(o, data.getString(table[i]));
} else if (tableUP[i].equals("amenities_id")) {
}
} catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException | SQLException e) {
log.error(e, errorMsg);
}
}
log.debug(o, "reflection");
data_in.add((Amenities) o);
}
Tables<Amenities> final_data = new Tables<Amenities>(data_in);
RestTemplate restTemplate = new RestTemplate();
postStatus=restTemplate.postForObject("http://" + upwsHost + ":" + upwsPort + "/amenities/", final_data, PostStatus.class);
return postStatus;
} catch (SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
errorMsg += "SQLState: " + ((SQLException) e).getSQLState();
errorMsg += "Error Code: " + ((SQLException) e).getErrorCode();
errorMsg += "Message: " + e.getMessage();
/*Throwable t = ex.getCause();
while (t != null) {
errorMsg += "Cause: " + t;
t = t.getCause();
}*/
}
}
log.error(ex, errorMsg+query);
}catch(Exception e){
log.error(e, errorMsg+query);
}
postStatus.status="Error";
postStatus.message=errorMsg+query;
return postStatus;
}
My code is failing when it sets the value of the integer attribute of the object Amenites using the code Integer scen=(Integer)data.getInt(tableUP[i]); f.set(o,scen );, when I check the results the other values are assigned properly but the value of the field scenario remains in null.
I am sure that the values from the database ResultSet exist, also I tryied setting a static integer value 66, and It only shows the field with a 0value.
Since I am pretty new on Java, I would appreciate you help to find what am I doing wrong?

Java SQLException: Result Set closed issue

I have this java function that runs and produces an error. I cannot figure out why this is occurring because this is the first function in the program to run so no other connections, statements, or result sets have been opened. The error is
Operation not allowed after ResultSet closed
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:768)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7008)
at equipmentinventoryimporter.Importer.sqlTable(Importer.java:219)
at equipmentinventoryimporter.Importer.main(Importer.java:58)
and the function is
private static void sqlTable(SQLTableJob sqltableJob) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connMySQL2 = null;
Statement stntMySQL2 = null;
try {
connMySQL2 = DriverManager.getConnection(mysqlAddress, mysqlUsername, mysqlPassword);
stntMySQL2 = connMySQL2.createStatement();
//MySQL Transaction
System.out.println("Starting " + sqltableJob.getMysqlTable() + " transaction");
stntMySQL2.execute("START TRANSACTION");
String insertQuery = "";
try {
final String inactiveQuery = "UPDATE `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "` SET `active`=0";
stntMySQL2.executeUpdate(inactiveQuery);
final ResultSet rs2 = stntMySQL2.executeQuery(sqltableJob.getSQLSelectQuery());
int counter = 0;
while (rs2.next()) {
counter++;
final String mysqlSetClause = sqltableJob.getMysqlSetClause(rs2);
insertQuery = "INSERT INTO `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "` SET " +
mysqlSetClause +
" ON DUPLICATE KEY UPDATE " +
mysqlSetClause;
stntMySQL2.executeUpdate(insertQuery);
if (counter % 5000 == 0) {
System.out.println("Processed " + counter + " rows.");
}
}
rs2.close();
if (!sqltableJob.isKeepInactives()) {
final String deleteQuery = "DELETE FROM `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "`" +
"WHERE `active`=0";
stntMySQL2.executeUpdate(deleteQuery);
}
stntMySQL2.execute("COMMIT");//last line of try block
System.out.println("Committed " + sqltableJob.getMysqlTable() + " transaction");
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Transaction level exception thrown.");
System.out.println(insertQuery);
stntMySQL2.execute("ROLLBACK");
System.out.println("MySQL query rolled back.");
}
//Another MySQL Transaction goes here
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Connection level exception thrown.");
} finally {
if (stntMySQL2 != null) {
try {
stntMySQL2.close();
} catch (Exception ex) {
}
}
if (connMySQL2 != null) {
try {
connMySQL2.close();
} catch (Exception ex) {
}
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Program level exception thrown.");
}
}
SQLTableJob is
package equipmentinventoryimporter;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* #author jmgreen
*/
public interface SQLTableJob {
public String getMysqlSchema();
public String getMysqlTable();
public String getSQLSelectQuery();
public String getMysqlSetClause(ResultSet rs) throws SQLException;
public boolean isKeepInactives();
}
and the specific SQLTableJob being referenced is
public class SQLTableJob10I implements SQLTableJob{
public boolean isKeepInactives() {
return true;
}
public String getMysqlSchema() {
return "Temp_Equipment_Inventory";
}
public String getMysqlTable() {
return "PC_Combined";
}
public String getSQLSelectQuery() {
final String sqlSelectQuery = "SELECT *" +
" FROM Temp_Equipment_Inventory.PC_Table10i";
return sqlSelectQuery;
}
public String getMysqlSetClause(ResultSet rs) throws SQLException {
final String mysqlSetClause =
"`Account_No`=" + Importer.sqlChar(rs.getString("Account_No")) +
",`Inventory_No`=" + Importer.sqlChar(rs.getString("Inventory_No")) +
",`Building_No`=" + Importer.sqlChar(rs.getString("Building_No")) +
",`Location`=" + Importer.sqlChar(rs.getString("Location")) +
",`FYYR_No`=" + Importer.sqlChar(rs.getString("FYYR_No")) +
",`Cost`=" + Importer.sqlChar(rs.getString("Cost")) +
",`Name`=" + Importer.sqlChar(rs.getString("Name")) +
",`Desc1`= ''" +
",`Desc2`= ''" +
",`Desc3`= ''" +
",`CDCATY`=" + Importer.sqlChar(rs.getString("CDCATY")) +
",`CDSRCE`=" + Importer.sqlChar(rs.getString("CDSRCE")) +
",`FLDCAL`=" + Importer.sqlChar(rs.getString("FLDCAL")) +
",`CDACQN`=" + Importer.sqlChar(rs.getString("CDACQN")) +
",`FLOWNR`=" + Importer.sqlChar(rs.getString("FLOWNR")) +
",`FLSHAR`=" + Importer.sqlChar(rs.getString("FLSHAR")) +
",`CDDELT`=" + Importer.sqlChar(rs.getString("CDDELT")) +
",`CNYTDT`=" + Importer.sqlChar(rs.getString("CNYTDT")) +
",`NOPURO`=" + Importer.sqlChar(rs.getString("NOPURO")) +
",`NOPIMO`=" + Importer.sqlChar(rs.getString("NOPIMO")) +
",`CDPREI`=" + Importer.sqlChar(rs.getString("CDPREI")) +
",`Original_Amount`=" + Importer.sqlChar(rs.getString("Original_Amount")) +
",`Serial_Code`=" + Importer.sqlChar(rs.getString("Serial_Code")) +
",`CDCOMP`=" + Importer.sqlChar(rs.getString("CDCOMP")) +
",`NOCHECK`=" + Importer.sqlChar(rs.getString("NOCHECK")) +
",`CDCOMM`=" + Importer.sqlChar(rs.getString("CDCOMM")) +
",`Last_Update`=" + Importer.sqlDate(rs.getString("Last_Update")) +
",`CDDEPT`=" + Importer.sqlChar(rs.getString("CDDEPT")) +
",`Room_No`=" + Importer.sqlChar(rs.getString("Room_No")) +
",`Date_Scanned`=" + Importer.sqlDate(rs.getString("Date_Scanned")) +
",`Date_Acquired`=" + Importer.sqlDate(rs.getString("Date_Acquired")) +
",`Manufacturer_Name`=" + Importer.sqlChar(rs.getString("Manufacturer_Name")) +
",`Expiry_Date`=" + Importer.sqlDate(rs.getString("Expiry_Date")) +
",`Active`='1'";
return mysqlSetClause;
}
}
From the Javadoc:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
From your code:
stntMySQL2.executeUpdate(inactiveQuery);
final ResultSet rs2 = stntMySQL2.executeQuery(sqltableJob.getSQLSelectQuery());
while (rs2.next()) {
...
stntMySQL2.executeUpdate(insertQuery);
You are re-executing stntMySQL2 inside the loop. This automatically closes rs2.
To fix, use a different statement object inside the loop.

Categories