SQL Exception . update row in jdbc - java

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 = ?")) {
// ...
}

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.

SQLException, No value for parameter 5

I'm using a UI that I've built to get input and MySQL to store the data locally. However, when I use the MySQL insert function, I'm encountering the following error:
java.sql.SQLException: No value specified for parameter 5
I only have four input fields, and four columns in the table; however, my debugger says I have seven value parameters. Here is the Insert statement:
private static final String GLInsert = "INSERT INTO gl_maint(GL_MAINT_NUM, GL_MAINT_NAME, GL_TYPE, BAL_FORWARD)"
+ "VALUES(?, ?, ?, ?) ON DUPLICATE KEY UPDATE "
+ "GL_MAINT_NAME = ?, GL_MAINT_TYPE = ?, BAL_FORWARD = ?";
And the preparedStatement method:
public void InsertGL(String ANstr, String ANAstr, String AIstr, double balfor) {
try {
conn = DriverManager.getConnection(ConnCheck, user, password);
GL_List = FXCollections.observableArrayList();
st = conn.prepareStatement(GLInsert);
st.setString(1, ANstr);
st.setString(2, ANAstr);
st.setString(3, AIstr);
st.setDouble(4, balfor);
st.executeUpdate();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(GLMaintAcct.class.getName()).log(Level.SEVERE, null, ex);
}
}
The issue is you have 7 parameters according to this query:
"INSERT INTO gl_maint(GL_MAINT_NUM, GL_MAINT_NAME, GL_TYPE, BAL_FORWARD)"
+ "VALUES(?, ?, ?, ?) ON DUPLICATE KEY UPDATE "
+ "GL_MAINT_NAME = ?, GL_MAINT_TYPE = ?, BAL_FORWARD = ?";
But you have just 4 value assigned like below:
st.setString(1, ANstr);
st.setString(2, ANAstr);
st.setString(3, AIstr);
st.setDouble(4, balfor);
You should add other 3 values like this providing their types:
st.setString(5, value5);
st.setDouble(6, value6);
st.setString(7, value7);

SQL Exception: the index is out of range

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 + " = ?";

java.sql.SQLException: Can not issue data manipulation statements with executeQuery(). 23

I have problem with my Programs . Help me please.
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
Class.forName("com.mysql.jdbc.Driver");
String path = "jdbc:mysql://localhost:3306/sampledb";
String Username = "root";
String Password = "";
Connection con = DriverManager.getConnection(path, Username, Password);
Statement s = con.createStatement();
String rGanTz = "UPDATE info SET Firstname = '"+txt_Firstname.getText()+"', Lastname = '"+txt_Lastname.getText()+"', Contact = '"+txt_Contact.getText()+"', WHERE '"+txt_Edpno.getText()+"'=EDPNO";
s.executeQuery(rGanTz);
JOptionPane.showMessageDialog(null,"Data has been successfully Updated","Update file", JOptionPane.INFORMATION_MESSAGE,null);
You should really consider what #OllieJones says in the comments about using prepared statements. #Rimas already gave you the solution so I will simply provide an example:
Connection con = DriverManager.getConnection(path, Username, Password);
String rGanTz = "UPDATE info SET Firstname = ?, Lastname = ?, Contact = ? " +
"WHERE EDPNO = ?";
PreparedStatement ps = con.prepareStatement(rGanTz);
ps.setString(1, txt_Firstname.getText());
ps.setString(2, txt_Lastname.getText());
ps.setString(3, txt_Contact.getText());
ps.setString(4, txt_Edpno.getText());
ps.executeUpdate();

Categories

Resources