SQL Exception: the index is out of range - java

When I run my program, it show the error the column is out of range. Connection is ok
For exmaple
updateRecoredtoStudent(15, "Annies","Bot"," Ionia", "1/1/2013","firstname","Anny")
private static void updateRecordToStudent(int studentid, String firstname, String lastname,String address, String dateofbirth, String cond_col, String cond_val) throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String updateTableSQL = "UPDATE student SET 'studentid' = ? 'firstname' = ? 'lastname' = ? 'address' = ? dateofbirth' = ? WHERE ? = ?";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, studentid);
preparedStatement.setString(2, firstname);
preparedStatement.setString(3, lastname);
preparedStatement.setString(4, address);
preparedStatement.setString(5, dateofbirth);
preparedStatement.setString(6, cond_col);
preparedStatement.setString(7, cond_val);
// execute update SQL stetement
preparedStatement.executeUpdate();
System.out.println("Record is updated to STUDENT table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
Student table contains
-studentid(int-PK)
-Firstname(String)
-lastname(String)
-Address(String)
-Dateofbirth(String)

String updateTableSQL = "UPDATE student SET studentid = ?, firstname = ?, lastname = ?, address = ?, dateofbirth = ? WHERE "+cond_col+" = ?";
preparedStatement.setInt(1, studentid);
preparedStatement.setString(2, firstname);
preparedStatement.setString(3, lastname);
preparedStatement.setString(4, address);
preparedStatement.setString(5, dateofbirth);
preparedStatement.setString(6, cond_val);
Only column values can be set. If you want to pass dynamic column name you should concat it with query. One more thing missing , between column name.

I think you wrong code statement. Please try the following.
String updateTableSQL = "UPDATE student SET 'studentid' = ? 'firstname' = ? 'lastname' = ? 'address' = ? dateofbirth' = ? WHERE " + cond_col + "= ?";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, studentid);
preparedStatement.setString(2, firstname);
preparedStatement.setString(3, lastname);
preparedStatement.setString(4, address);
preparedStatement.setString(5, dateofbirth);
preparedStatement.setString(6, cond_val);

Change your SQL syntax to be like this:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
So your SQL UPDATE query will be:
String updateTableSQL = "UPDATE student SET studentid=?, firstname=?, lastname=?, address=?, dateofbirth=? WHERE " + fieldName + " = ?";

Related

How to use getParameterNames() value

I am getting parameters name and values from from UI to my servlet using getParameterNames. Now I want to use those values to run my query but I don't know how to do that I am getting errors while doing that
What I am doing
From Ui having Dynamic stars so getting values using getParameterNames(), then try to use that values.
If user selects 5 stars I am getting its parameter and its values as 1 because excellent is defined as 1 in my data base very good as 2 and so on to poor as 5.
So I am getting values as after click on save
Parameter Name is 'Quality Of Food' and Parameter Value is '3'
Parameter Name is 'Cleanliness' and Parameter Value is '3'
Parameter Name is 'Service' and Parameter Value is '3'
Parameter Name is 'Staf Behavior' and Parameter Value is '3'
Parameter Name is 'Ambience' and Parameter Value is '2'
Now I am running a query in my Java servlet doPost class to get respective attributes to values. For example, for value 2 attribute name is excellent like that.
After that I have to insert all this data into my db.
The main thing is all the stars are dynamic as coming from database as JSON so it can vary currently I am having 5 attributes of 5-5 stars to show on UI on click of submit getting data in back end
My code
Connection con = null;
Statement statement = null;
java.util.Date dateUtil = new Date();
java.sql.Date dateSql = new java.sql.Date(dateUtil.getTime());
java.sql.Timestamp timestamp = new Timestamp(dateUtil.getTime());
try {
con = DBConnection.createConnection();
statement = con.createStatement();
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()) {
Object objOri = en.nextElement();
String param = (String) objOri;
String value = request.getParameter(param);
System.out.println("Parameter Name is '" + param + "' and Parameter Value is '" + value + "'");
String getSql = "select ATTRIBUTENAME from FEEDBACKATTRUBUTES where POSITIONNO=" + value
+ " and ATTRIBUTETYPE ='STARRING'";
String updateSql = "INSERT INTO CUSTOMERFEEDBACK (CUSTOMERID, CUSTOMERNAME, BILLNO, BILLDATE, ATTRIBUTE1, ATTRIBUTE2, ATTRIBUTE3, ATTRIBUTE4, ATTRIBUTE5, ATTRIBUTE6, ATTRIBUTE7, ATTRIBUTE8, ATTRIBUTE9, ATTRIBUTE10, REMARKS, CREATEDTIMESTAMP, SMSSENT)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
ResultSet resultSet = statement.executeQuery(getSql);
while (resultSet.next()) {
String attributeName = resultSet.getString("ATTRIBUTENAME");
PreparedStatement ps = con.prepareStatement(updateSql);
ps.setString(1, "123456");
ps.setString(2, "Dheeraj");
ps.setString(3,"-");
ps.setDate(4,dateSql);
ps.setString(5, param+":"+attributeName); //how can i insert these values
ps.setString(6, param+":"+attributeName);
ps.setString(7, param+":"+attributeName);
ps.setString(8, param+":"+attributeName);
ps.setString(9, param+":"+attributeName);
ps.setString(10, param+":"+attributeName);
ps.setString(11, param+":"+attributeName);
ps.setString(12, param+":"+attributeName);
ps.setString(13, param+":"+attributeName);
ps.setString(14, param+":"+attributeName);
ps.setString(15, "remark");
ps.setTimestamp(16, timestamp);
ps.setString(17, "N");
ps.addBatch();
ps.executeBatch();
}
}
} catch (SQLException e) {
System.out.println("SQL EXCPTION 91");
e.printStackTrace();
}
As in my code you can check from ps.setString(5, param+":"+attributeName); //how can I insert these values this line param and value (attribute name I am inserting) but I have got only 5 attributes values from UI for all others I have to insert -.
My main issue is currently I am having only five attributes on my UI but here in Java class insert query I have to insert 5 and other as null or -.
For better understanding, this is my UI.
You need to modify the sequence of the process, first you need to store the params and their values locally and then add them to the prepared statement before executing it.
Here is a modified version of your code that does it:
Connection con = null;
Statement statement = null;
java.util.Date dateUtil = new Date();
java.sql.Date dateSql = new java.sql.Date(dateUtil.getTime());
java.sql.Timestamp timestamp = new Timestamp(dateUtil.getTime());
try {
con = DBConnection.createConnection();
statement = con.createStatement();
Enumeration en = request.getParameterNames();
LinkedHashMap<String, Integer> evaluation = new LinkedHashMap<>();
HashMap<Integer,String > classifications = new HashMap<>();
String getSql = "select ATTRIBUTENAME,POSITIONNO from FEEDBACKATTRUBUTES where ATTRIBUTETYPE ='STARRING'";
ResultSet resultSet = statement.executeQuery(getSql);
while (resultSet.next()) {
classifications.put(resultSet.getInt("POSITIONNO"),resultSet.getString("ATTRIBUTENAME"));
}
while (en.hasMoreElements()) {
Object objOri = en.nextElement();
String param = (String) objOri;
String value = request.getParameter(param);
System.out.println("Parameter Name is '" + param + "' and Parameter Value is '" + value + "'");
evaluation.put(param,Integer.parseInt(value));
}
String updateSql = "INSERT INTO CUSTOMERFEEDBACK (CUSTOMERID, CUSTOMERNAME, BILLNO, BILLDATE, ATTRIBUTE1, ATTRIBUTE2, ATTRIBUTE3, ATTRIBUTE4, ATTRIBUTE5, ATTRIBUTE6, ATTRIBUTE7, ATTRIBUTE8, ATTRIBUTE9, ATTRIBUTE10, REMARKS, CREATEDTIMESTAMP, SMSSENT)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(updateSql);
ps.setString(1, "123456");
ps.setString(2, "Dheeraj");
ps.setString(3,"-");
ps.setDate(4,dateSql);
Iterator<Map.Entry<String, String>> evaluationIterator = evaluation.entrySet().iterator();
int i = 5;
while (i<15) {
if(evaluationIterator.hasNext()){
Map.Entry<String, String> entry = evaluationIterator.next();
ps.setString(i, entry.getKey()+":"+classifications.get(entry.getValue()));
}
else{
ps.setString(i, "");
}
i++;
}
ps.setString(15, "remark");
ps.setTimestamp(16, timestamp);
ps.setString(17, "N");
ps.addBatch();
ps.executeBatch();
} catch (SQLException e) {
System.out.println("SQL EXCPTION 91");
e.printStackTrace();
}
please let me know if this works for you, note that the code is not tested and could contain errors.

how to pass the id value using name from one table to another table and store the information to database [duplicate]

This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 4 years ago.
Sql query how to pass the id from department table using the department name to the user table using the department id
here in department table dept_id is primary key
and dept_id in user table is foreign key
how to select the dept_id using department_name from the department table and store the value in the user table
try{
Connection con = DBconnect.getConnection();
//selecting the dpartment
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
String s11=comboboxdeptid.getItems().toString();
ResultSet rs=ps.executeQuery();
if(rs.next()==true)
{
if(rs.getString("DEPARTMENT_NAME").equals(comboboxdeptid.getSelectionModel().toString()))
rs.getString("DEPARTMENT_CODE");
}
//second stmt
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
String s12 = nameid.getText();
String s13 = Firstnameid.getText();
String s14 = Lnameid.getText();
String s15 = desigid.getText();
String s16 = comboboxdeptid.getItems().toString();
String s17 = addrsid.getText();
String s18 = passwordid.getText();
ps.setString(1, s12);
ps.setString(2, s13);
ps.setString(3, s14);
ps.setString(4, s15);
ps.setString(5, s17);
ps.setString(6, s18);
ps.setString(7, s11);
ps.setString(8, "abc");
ps.execute();
ResultSet rs1=ps1.executeQuery();
//third stmt
String sql2 = "update security_qa_info set SECURITY_QUESTION=?, SECURITY_ANSWER=? where USER_ID=?";
PreparedStatement ps2 = con.prepareStatement(sql2);
String s19 = securityquestionid.getSelectionModel().getSelectedItem().toString();
String s20 = answerid.getText();
while(rs2.next()==true)
{
if(rs2.getString("USER_NAME").equals(nameid.getText()))
{
rs2.getString("USER_ID");
ps2.setString(1, s16);
}
}
ps2.setString(2, s19);
ps2.setString(3, s20);
ps2.executeUpdate();
showMessageDialog(null, "Registration Successful");
}catch(Exception e){
// showMessageDialog(null, e);
e.printStackTrace();
}
Parent fxml = FXMLLoader.load(getClass().getResource("/com/abc/fxml/LoginPage.fxml"));
pane2.getChildren().setAll(fxml);
} else {
showMessageDialog(null, "Passwords don't match!");
}
}
ps = prepared statement for SELECT query:
String sql ="select DEPARTMENT_CODE,DEPARTMENT_NAME from department_info";
PreparedStatement ps = con.prepareStatement(sql);
ps1 = prepared statement for INSERT statement:
String sql1 = "insert into user_info(USER_NAME, FIRST_NAME, LAST_NAME, DESIGNATION, ADDRESS,PASSWORD_TXT,DEPARTMENT_CODE,CREATED_BY) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps1 = con.prepareStatement(sql1);
Using the wrong prepared statement:
ps.setString(1, s12);
A suggestion - if you call the first prepared statement 'selectDepartmentDetails' and the second 'insertUserInfo', it is less likely you will run into this.

SQL Exception . update row in jdbc

I need to write a query to update a row in the database. but exception is
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Erreur de syntaxe pr?s de 'SET eMail = '11111', SET phoneNumber = '111111' WHERE name = 'Saba', surname= 'M' ? la ligne 1 .
what is the problem?
public static void updateUser(User user, Connection connection) throws SQLException {
PreparedStatement ps = null;
ps = connection.prepareStatement("UPDATE USERS SET login = ?, SET eMail = ?, SET phoneNumber = ? WHERE name = ?, surname= ?");
ps.setString(1, user.getLogin());
ps.setString(2, user.geteMail());
ps.setString(3, user.getPhoneNumber());
ps.setString(4, user.getName());
ps.setString(5, user.getSurname());
ps.executeUpdate();
The UPDATE statement only has a single SET clause. You repeated the SET keyword, which is wrong. Besides, you forgot the AND keyword to combine predicates. Write this instead:
try (PreparedStatement ps = connection.prepareStatement(
"UPDATE USERS "
+ "SET login = ?, eMail = ?, phoneNumber = ? "
+ "WHERE name = ? AND surname = ?")) {
// ...
}

column not allowed here oracle with getText

I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql;
sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";
stmt = conn.createStatement();
emps = stmt.executeQuery(sql);
String ISBN= txt_isbn.getText();
String DISPONIBILITA= txt_disp.getText();
String TITOLO= txt_titolo.getText();
String CASA_EDITRICE= txt_casa.getText();
String CODICE_AUTORE= txt_autore.getText();
String GENERE= txt_genere.getText();
String PREZZO = txt_prezzo.getText();
JOptionPane.showMessageDialog(null, "SALVATO");
}catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null, e);
}
finally
{
try{
if (emps != null)
emps.close();
}
catch (SQLException e) { }
try
{
if (stmt != null)
stmt.close();
}
catch (SQLException e) { }
}
Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?
You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
Example
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "MindPeace");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement .executeUpdate();
2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.
String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
+ "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.createStatement()) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
String ISBN = txt_isbn.getText();
String DISPONIBILITA = txt_disp.getText();
String TITOLO = txt_titolo.getText();
String CASA_EDITRICE = txt_casa.getText();
String CODICE_AUTORE = txt_autore.getText();
String GENERE = txt_genere.getText();
BigDecimal PREZZO = new BigDecimal(
numberFormat.parse(txt_prezzo.getText()).doubleValue())
.setScale(2);
stmt.setString(1, ISBN);
stmt.setString(2, DISPONIBILITA);
stmt.setString(3, TITOLO);
stmt.setString(4, CASA_EDITRICE);
stmt.setString(5, CODICE_AUTORE);
stmt.setString(6, GENERE);
stmt.setBigDecimal(7, PREZZO);
int updateCount = stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
1234.50,
...)
for:
"De'l Rey"
1.234,50
updateCount should be 1 on success.
Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
try{
sql= delete......
etc
if (!found)
JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql= "DELETE FROM progetto.libro WHERE isbn =?"; /
pst=(OraclePreparedStatement) conn.prepareStatement(sql);
pst.setString (1, txt_isbn.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "ELIMINATO");
Update_table();
txt_isbn.setText("");
txt_disp.setText("");
txt_titolo.setText("");
txt_casa.setText("");
txt_autore.setText("");
txt_genere.setText("");
txt_prezzo.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again

Why do I keep getting this cursed SQL*Plus invalid identifier error?

I keep getting a invalid identifier exception when I try to run the below script:
javax.servlet.ServletException: java.sql.SQLException: [Oracle][ODBC][Ora]ORA-00904: "CUSTID": invalid identifier
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:rreOracle","xxxxxx","xxxxxxxx");
stmt = conn.createStatement();
PreparedStatement preparedStatement;
//get parameters from the request
String custID=request.getParameter("cust_ID");
String saleID=request.getParameter("sale_ID");
String firstName=request.getParameter("first_Name");
String mInitial=request.getParameter("mI");
String lastName=request.getParameter("last_Name");
String streetName=request.getParameter("street");
String city=request.getParameter("city");
String state=request.getParameter("state");
String zipCode=request.getParameter("zip_Code");
String DOB=request.getParameter("DOB");
String agentID=request.getParameter("agent_ID");
String homePhone=request.getParameter("home_Phone");
String cellPhone=request.getParameter("cell_Phone");
String profession=request.getParameter("profession");
String employer=request.getParameter("employer");
String referrer=request.getParameter("referrer");
preparedStatement = conn.prepareStatement("UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=?, customer.first_Name=?, customer.mI=?, customer.last_Name=?, customer.street_Name=?, customer.city=?, customer.state=?, customer.zip_Code=?,customer. DOB=?, customer.agent_ID=?, customer.home_Phone=?, customer.cell_Phone=?, customer.profession=?, customer.employer=?, customer.referrer=?"
+ " WHERE customer.cust_ID=custID ") ;
preparedStatement.setInt(1, Integer.valueOf(custID));
preparedStatement.setInt(2, Integer.valueOf(saleID));
preparedStatement.setString(3, firstName);
preparedStatement.setString(4, mInitial);
preparedStatement.setString(5, lastName);
preparedStatement.setString(6, streetName);
preparedStatement.setString(7, city);
preparedStatement.setString(8, state);
preparedStatement.setString(9, zipCode);
preparedStatement.setString(10, DOB);
preparedStatement.setInt(11, Integer.valueOf(agentID));
preparedStatement.setString(12, homePhone);
preparedStatement.setString(13, cellPhone);
preparedStatement.setString(14, profession);
preparedStatement.setString(15, employer);
preparedStatement.setString(16, referrer);
preparedStatement.executeUpdate();
you can try
<%preparedStatement = conn.prepareStatement("UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=?, customer.first_Name=?, customer.mI=?, customer.last_Name=?, customer.street_Name=?, customer.city=?, customer.state=?, customer.zip_Code=?,customer. DOB=?, customer.agent_ID=?, customer.home_Phone=?, customer.cell_Phone=?, customer.profession=?, customer.employer=?, customer.referrer=?"
+ " WHERE customer.cust_ID=?") ;%>
<%preparedStatement.setString(17, custID );%>
or
<%preparedStatement = conn.prepareStatement("UPDATE customer"
+ " SET customer.cust_ID=?, customer.sale_ID=?, customer.first_Name=?, customer.mI=?, customer.last_Name=?, customer.street_Name=?, customer.city=?, customer.state=?, customer.zip_Code=?,customer. DOB=?, customer.agent_ID=?, customer.home_Phone=?, customer.cell_Phone=?, customer.profession=?, customer.employer=?, customer.referrer=?"
+ " WHERE customer.cust_ID="+custID ) ;%>
Hope it helps.
In this part of your statement "WHERE customer.cust_ID=custID" oracle is looking for a value called "custID".
At that point,the variable names in your context aren't relevant - inside the SQL an "where A=B" statement refers to "column A == column B" - since there's not "custID" column in the table, oracle complains.

Categories

Resources