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
Related
I cant get the data on my table when using setString() method it says that indexOutOfBoundsException
String upd = "update sinfo set sname = ?, course = ?, section = ?, dob = ?, address = ? where sid = ?";
String sc = course.getSelectedItem().toString();
TableModel model = sTable.getModel();
int i = sTable.getSelectedRow();
pst = conn.prepareStatement(upd);
pst.setString(1, sn.getText());
pst.setString(2, sc);
pst.setString(3, ss.getText());
pst.setString(4, db.getText());
pst.setString(5, ad.getText());
pst.setString(6, model.getValueAt(i,0).toString()); //I get the error here saying indexOutOfBoundsException: -1
pst.executeUpdate();
I already fixed it, camickr is right. Whenever I select a row on a table, the selected row will reset. And that is the cause of the error. Thank you and sorry because im new to programming and using this site😅
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.
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'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);
How can i put into code when i want to prompt a message whenever a user creates a new account or updates his/her username and that username already exist on the sql database.
here's a part of my code when i click save button on my CreateNewUserAccount class:
String sql = "insert into tblUserInfo (UserID, LastName, FirstName, PositionID, Username, Password) values(?, ?, ?, ?, ?, ?) " ;
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtUserID.getText());
pst.setString(2, txtLastName.getText());
pst.setString(3, txtFirstName.getText());
pst.setString(4, (String) comboPosition.getSelectedItem().toString().substring(0, 1));
pst.setString(5, txtUsername.getText());
pst.setString(6, txtPassword.getText());
pst.execute();
if(txtConfirmPassword.getText().equals(txtPassword.getText())){
JOptionPane.showMessageDialog(null, "Saved New User Account");
clear();
}
else{
JOptionPane.showMessageDialog(null, "Incompatible Password");
txtConfirmPassword.setText("");
}
//UpdateEmployeeTable();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
and also my UserAccount class where user can update/edit their information including their username:
String sql = "update tblUserInfo set LastName = ?, FirstName = ?, PositionID = ?, Username = ?, Password = ? where UserID= ?";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, txtLastName.getText());
pst.setString(2, txtFirstName.getText());
pst.setString(3, (String) comboPos.getSelectedItem().toString().substring(0, 1));
pst.setString(4, txtUserName.getText());
pst.setString(5, txtPassword.getText());
pst.setString(6, txtUserID.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "User Account Updated");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
how can i put a checking on this? Thanks in advance
I would use something like this
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
http://blogs.msdn.com/b/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx
One option is to do a count query of that username where the user id isn't the same, such as this:
select count(Username) from tblUserInfo where UserId != ?
If you find a result greater than zero, that user id is used by someone else, display the warning.
you can do like that
Statement st=con.getConnection(.....);
String query= "select username from tables where username="uservalue"";
ResultSet rs=st.executeQuery(query);
int value=0;
while(rs.next())
{
value++;
}
if(value>1)
{
String query= "select username from tables where username="uservalue"";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
String user=rs.getString("username");
}
String updatequery="update tables set username="updatevalue" where username="updatevalue"";
int q=st.executeupdate(updatequery);
}
else
{
insert query..........
}