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.
Related
My app allows users to create an account (stored in database) and place orders.
When a client registers himself, I want to generate a primary key named CLIENT_CODE to identify him, starting from x value and increment it with y value. (I'm using oracle 11g atm)
I've tried this so far:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String fname = jTextField9.getText();
String lname = jTextField10.getText();
String city = jTextField11.getText();
String street = jTextField13.getText();
String number = jTextField14.getText();
String userClient = jTextField15.getText();
String pass1 = String.valueOf(jPasswordField5.getPassword());
String pass2 = String.valueOf(jPasswordField6.getPassword());
if(verifyFields()){
if(!checkUsername(userClient)){
OraclePreparedStatement ps;
OracleResultSet rs;
String registerClient = "insert into CLIENT (FNAME_CL, LNAME, CITY, STREET, NUMBER, MONEY, CLIENT_CODE, USER_CLIENT, PASS) values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
ps = (OraclePreparedStatement) JavaConnectDb.ConnectDb().prepareStatement(registerClient);
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, city);
ps.setString(4, street);
ps.setString(5, number);
ps.setDouble(6, 0.0);
ps.setInt(7, ???); <--- here should be the generated primary key
ps.setString(8, userClient);
ps.setString(9, pass1);
if(ps.executeUpdate() != 0){
JOptionPane.showMessageDialog(null, "Account created!");
} else{
JOptionPane.showMessageDialog(null, "Error: Check your info");
}
} catch (SQLException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Don't do it in Java; handle the primary key value creation in the database using a sequence:
CREATE SEQUENCE CLIENT__CLIENT_CODE__SEQ
START WITH 1
INCREMENT BY 1
Then just use your sequence in the INSERT statement and use the RETURNING clause to get the generated value as an OUT parameter of your prepared statement.
insert into CLIENT (
FNAME_CL,
LNAME,
CITY,
STREET,
NUMBER,
MONEY,
CLIENT_CODE,
USER_CLIENT,
PASS
) values (
?,
?,
?,
?,
?,
?,
CLIENT__CLIENT_CODE__SEQ.NEXTVAL,
?,
?
) RETURNING CLIENT_CODE INTO ?
If you were using Oracle 12c then you could use GENERATED AS IDENTITY in the table's CREATE DDL statement to generate the values without creating a separate sequence.
I am using the prepared statement to store some variables into the database. The program runs without any errors but the database wont update.
public void setData(Dealer sDealer)
{
String fName = sDealer.getFirstName();
String lName = sDealer.getLastName();
int age = sDealer.getAge();
int xp = sDealer.getExperience();
String mStatus = sDealer.getMartialStatus();
String dAdd = sDealer.getAddress();
String pNum = sDealer.getPhoneNumber();
String email = sDealer.getEmailAddress();
String crime = sDealer.getCriminalRecord();
String type = sDealer.getCategory();
String SQL ="INSERT INTO DEALERS ("
+"firstName, " +"lastName ," +"dAge, "
+"dXp, " +"maritalStatus , " +"dAddress, "
+"phoneNumber, " +"dMail, " +"criminalRecord, " +"dType )"
+"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try{
My suspicion is on the following prepared statement I used in this method but I am unable to figure out just what I am doing wrong.
PreparedStatement pStat = dConnect.prepareStatement(SQL);
pStat.setString(1, fName);
pStat.setString(2, lName);
pStat.setInt(3, age);
pStat.setInt(4, xp);
pStat.setString(5, mStatus);
pStat.setString(6, dAdd);
pStat.setString(7, pNum);
pStat.setString(8, email);
pStat.setString(9, crime);
pStat.setString(10, type);
}catch(Exception sx){
System.out.println("Error is found :"+sx);
}
}
You need to execute the statement and commit these database changes by adding lines in try-catch block:
pStat.executeUpdate();
dConnect.commit();
You just need to execute the statement by adding one additional call:
pStat.executeUpdate();
I have been trying to solve this for hours and I have no idea why this is happening. I keep on getting this error when trying to update one of my "Employees" with my GUI that I made.
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: 'test'
Whenever I click an employee in my TableView, and then change the field of something, I would get that. Here is a picture of my GUI:
Nothing in my data table is a DOUBLE, they all are like this:
I have googled everywhere and it all says it relates to syntax for my SQL query but that looks fine so I do not know why.
Here is the code for my Update button:
public void handleUpdateEmployee(ActionEvent event) {
String sql = "UPDATE employees set firstName = ?, lastName = ?, gender = ?, age = ?, position = ?, image = ? where employeeNum =?";
try {
Integer employeeNum = Integer.valueOf(employeeNumField.getText());
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
String gender = genderField.getText();
Integer age = Integer.valueOf(ageField.getText());
String position = positionField.getText();
String image = imageField.getText();
pst = con.prepareStatement(sql);
pst.setInt(1, employeeNum);
pst.setString(2, firstName);
pst.setString(3, lastName);
pst.setString(4, gender);
pst.setInt(5, age);
pst.setString(6, position);
pst.setString(7, image);
pst.executeUpdate();
loadEmployeeData();
} catch (SQLException e) {
e.printStackTrace();
}
}
Would appreciate any help and if you need any more details, let me know!
You bound your query parameters in the wrong order. Look closely at the statement and then the updated code which follows:
String sql = "UPDATE employees set firstName = ?, lastName = ?, gender = ?, ";
sql += "age = ?, position = ?, image = ? where employeeNum =?";
pst.setString(1, firstName); // first parameter (?) in statement
pst.setString(2, lastName);
pst.setString(3, gender);
pst.setInt(4, age);
pst.setString(5, position);
pst.setString(6, image);
pst.setInt(7, employeeNum); // LAST parameter (?) in statement
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);
I have a problem during an insert in Oracle using Java and JDBC. The error obtained is:
java.sql.SQLException: ORA-00917: missing comma
The data for the insert is taken from a form like a string and is parsed to the appropiated data type and then is saved in an object called edicio. That's all OK. Then, my intention is make an insert in the DB using the data of this object.
Here is the code of the DAO, where I'm making the insert:
public Edicio insertarCurs(Connection con, Edicio ed) throws SQLException {
PreparedStatement stm = null;
ResultSet rst = null;
// Insert
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO curs (id, nom, idarea, area, programa, datainici)");
sql.append(" VALUES (?, ?, ?, ?, ?, ?");
logger.info("Building insert works fine.");
try {
stm = con.prepareStatement(sql.toString());
// params
stm.setLong(1, ed.getIdEdicio());
stm.setString(2, ed.getNomEdicio());
stm.setLong(3, ed.getIdArea());
stm.setString(4, ed.getArea());
stm.setString(5, ed.getPrograma());
// Conversion from Java Date to SQL Date
java.sql.Date sqlDate = new java.sql.Date(ed.getDataInici().getTime());
logger.info("sqlDate before the insert is: "+ sqlDate); //0011-12-02
stm.setDate(6, sqlDate);
// Data and results commented
logger.info("Id edicio: "+ ed.getIdEdicio()); //6
logger.info("Nom edicio: "+ ed.getNomEdicio()); //test
logger.info("Id area: "+ ed.getIdArea()); //0
logger.info("Nom area: "+ ed.getArea()); //test
logger.info("Programa: "+ ed.getPrograma()); //test
logger.info("Data inici: "+ sqlDate); //2011-06-06
// We are going to execute the insert
int numRows = stm.executeUpdate();
// The program never reaches this point, fails doing the executeUpdate()
logger.info("Rows created: "+ numFiles);
...
The variable types are:
idEdicio = long
nomEdicio = String
idArea = long
area = String
programa = String
dataInici = Date
Can someone help me? Thank you in advance :)
Missing )
sql.append(" VALUES (?, ?, ?, ?, ?, ?");
should be
sql.append(" VALUES (?, ?, ?, ?, ?, ?)");
sql.append(" VALUES (?, ?, ?, ?, ?, ?)");
^--- missing parenthesis