Java Prepared Statement Cannot Update Database - java

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();

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.

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);

How make a update using java netbeans and sqlservel

I want to make a CRUD in netbeans and sqlserver,I have already learnt how make the inserts and deletes but I haven't abled to solve the update.Help me please.
These are my codes:
name database abarrotes, table producto.
Method update:
public void ModificarProducto (Producto c){
try{
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/abarrotes", "root", "123");
String sentencia = "UPDATE producto SET Nombre_Producto= ?, Marca_Producto = ?, Presentacion_Producto=?, Precio_Producto=?, Punto_de_Reorden = ?, Existencia = ? where Id_Producto=?;";
PreparedStatement pstm = con.prepareStatement(sentencia);
pstm.setInt(1, c.getId_Producto());
pstm.setString(2, c.getNombre_Producto());
pstm.setString(3, c.getMarca_Producto());
pstm.setString(4, c.getPresentacion_Producto());
pstm.setFloat(5, c.getPrecio_Producto());
pstm.setInt(6, c.getPunto_de_Reorden());
pstm.setInt(7, c.getExistencia());
pstm.execute();
pstm.close();
} catch(SQLException e){
System.out.println(e);
}
}
The frame's boton
OperacionesProducto basedatos = new OperacionesProducto();
private void Btn_InsertarActionPerformed(java.awt.event.ActionEvent evt) {
Producto prod = new Producto();
prod.setId_Producto(Integer.parseInt(Id_Producto.getText()));
prod.setNombre_Producto(Nombre_Producto.getText());
prod.setMarca_Producto(Marca_Producto.getText());
prod.setPresentacion_Producto(Presentacion_Producto.getText());
prod.setPrecio_Producto(Float.parseFloat(Precio_Producto.getText()));
prod.setPunto_de_Reorden(Integer.parseInt(Punto_de_Reorden.getText()));
prod.setExistencia(Integer.parseInt(Existencia.getText()));
basedatos.InsertarProducto(prod);
}
DOESN'T MARK ANY ERROR BUT THE DATABASE DOESN'T CHANGE
HELP ME PLEASE :).
The order of the ? in the query string doesn't match the indexes of the set commands. I think the first needs to be last and everything else moved up one to make all the names match. Change to:
String sentencia = "UPDATE producto SET "
+ "Nombre_Producto= ?, "
+ "Marca_Producto = ?, "
+ "Presentacion_Producto=?, "
+ "Precio_Producto=?, "
+ "Punto_de_Reorden = ?, "
+ "Existencia = ? "
+ "where Id_Producto=?;";
PreparedStatement pstm = con.prepareStatement(sentencia);
pstm.setString(1, c.getNombre_Producto());
pstm.setString(2, c.getMarca_Producto());
pstm.setString(3, c.getPresentacion_Producto());
pstm.setFloat(4, c.getPrecio_Producto());
pstm.setInt(5, c.getPunto_de_Reorden());
pstm.setInt(6, c.getExistencia());
pstm.setInt(7, c.getId_Producto());

Get RETURNING value from Postgresql via Java

From Java, I'm calling a prepared statement in Postgresql with an insert that has a RETURNING clause for my identity column. In PG admin it comes right back, but not sure how to get it from my prepared statement:
String insertStatement = "INSERT INTO person(\n" +
" name, address, phone, customer_type, \n" +
" start_dtm)\n" +
" VALUES (?, ?, ?, ?, \n" +
" ?)\n" +
" RETURNING person_id;";
PreparedStatement stmt = connection.prepareStatement(insertStatement);
stmt.setObject(1, perToSave.getName(null));
stmt.setObject(2, editToSave.getAddress());
stmt.setObject(3, editToSave.getPhone());
stmt.setObject(4, editToSave.getCustType());
long epochTime = java.lang.System.currentTimeMillis();
stmt.setObject(5, new java.sql.Date(epochTime));
stmt.executeUpdate();
I do not have enough reputation to Comment and my Edit got rejected, so sorry for re-posting the already accepted answer from hd1.
executeUpdate expects no returns; use execute.
Check if there is some results before trying to retrieve the value.
String insertStatement = "INSERT INTO person(\n" +
" name, address, phone, customer_type, \n" +
" start_dtm)\n" +
" VALUES (?, ?, ?, ?, \n" +
" ?)\n" +
" RETURNING person_id;";
PreparedStatement stmt = connection.prepareStatement(insertStatement);
stmt.setObject(1, perToSave.getName(null));
stmt.setObject(2, editToSave.getAddress());
stmt.setObject(3, editToSave.getPhone());
stmt.setObject(4, editToSave.getCustType());
long epochTime = java.lang.System.currentTimeMillis();
stmt.setObject(5, new java.sql.Date(epochTime));
stmt.execute();
ResultSet last_updated_person = stmt.getResultSet();
if(last_updated_person.next()) {
int last_updated_person_id = last_updated_person.getInt(1);
}
According to the javadoc, PreparedStatement inherits from Statement and the latter contains a getResultSet() method. In other words, try this:
String insertStatement = "INSERT INTO person(\n" +
" name, address, phone, customer_type, \n" +
" start_dtm)\n" +
" VALUES (?, ?, ?, ?, \n" +
" ?)\n" +
" RETURNING person_id;";
PreparedStatement stmt = connection.prepareStatement(insertStatement);
stmt.setObject(1, perToSave.getName(null));
stmt.setObject(2, editToSave.getAddress());
stmt.setObject(3, editToSave.getPhone());
stmt.setObject(4, editToSave.getCustType());
long epochTime = java.lang.System.currentTimeMillis();
stmt.setObject(5, new java.sql.Date(epochTime));
stmt.execute();
ResultSet last_updated_person = stmt.getResultSet();
last_updated_person.next();
int last_updated_person_id = last_updated_person.getInt(1);
Leave a comment if you have further issues.
Calling executeUpdate() expects no result from statement. Call stmt.execute() and then stmt.getResultSet()
JDBC has built-in support for returning primary key values for insert statements. Remove the "returning" clause from your SQL and specify PreparedStatement.RETURN_GENERATED_KEYS as a second parameter to your prepareStatment(...) call. Then you can get the generated primary key by calling stmt.getGeneratedKeys() on your PreparedStatement object after calling executeUpdate().
String insertStatement = "INSERT INTO person(\n" +
" name, address, phone, customer_type, \n" +
" start_dtm)\n" +
" VALUES (?, ?, ?, ?, \n" +
" ?)";
PreparedStatement stmt = connection.prepareStatement(insertStatement,
PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setObject(1, perToSave.getName(null));
stmt.setObject(2, editToSave.getAddress());
stmt.setObject(3, editToSave.getPhone());
stmt.setObject(4, editToSave.getCustType());
long epochTime = java.lang.System.currentTimeMillis();
stmt.setObject(5, new java.sql.Date(epochTime));
stmt.executeUpdate();
ResultSet resultSet = stmt.getGeneratedKeys();
resultSet.next();
int lastInsertedPersonID = resultSet.getInt(1);

How to optimize this update SQL query

I have this Java method which I will use to insert data from JSF form into Oracle:
public int saveData(int result) throws SQLException, java.text.ParseException, NoSuchAlgorithmException {
String SqlStatement = null;
if (ds == null) {
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException();
}
PreparedStatement ps = null;
/*
CREATE TABLE USERS(
USERID INTEGER NOT NULL,
GROUPID INTEGER,
SPECIALNUMBER VARCHAR2(60 ),
USERNAME VARCHAR2(50 ),
PASSWD VARCHAR2(50 ),
DATETOCHANGEPASSWD DATE,
ADDRESS VARCHAR2(60 ),
STATEREGION VARCHAR2(50 ),
COUNTRY VARCHAR2(50 ),
USERSTATUS VARCHAR2(30 ),
TELEPHONE VARCHAR2(50 ),
DATEUSERADDED DATE,
USEREXPIREDATE DATE,
DATEUSERLOCKED CHAR(20 ),
CITY VARCHAR2(50 ),
EMAIL VARCHAR2(50 ),
DESCRIPTION CLOB
)
/
*/
try {
conn.setAutoCommit(false);
boolean committed = false;
try { /* insert into Oracle the default system(Linux) time */
InsertSqlStatement = "INSERT INTO USERS"
+ " (USERID, GROUPID, SPECIALNUMBER, USERNAME, PASSWD, DATETOCHANGEPASSWD,"
+ " ADDRESS, STATEREGION, COUNTRY, USERSTATUS, TELEPHONE, DATEUSERADDED,"
+ " USEREXPIREDATE, DATEUSERLOCKED, CITY, EMAIL, DESCRIPTION)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
UpdateSqlStatement = "UPDATE USERS "
+ "SET "
+ "USERID = ?, "
+ "GROUPID = ?, "
+ "SPECIALNUMBER = ?, "
+ "USERNAME = ?, "
+ "PASSWD = ?, "
+ "DATETOCHANGEPASSWD = ?, "
+ "ADDRESS = ?, "
+ "STATEREGION = ?, "
+ "COUNTRY = ?, "
+ "USERSTATUS = ?, "
+ "TELEPHONE = ?, "
+ "DATEUSERADDED = ?, "
+ "USEREXPIREDATE = ?, "
+ "DATEUSERLOCKED = ?, "
+ "CITY = ?, "
+ "EMAIL = ?, "
+ "DESCRIPTION = ? "
+ "WHERE USERID = " + id;
ps = conn.prepareStatement(SqlStatement);
ps.setString(1, settingsMap.get("USERID"));
ps.setString(2, settingsMap.get("GROUPID"));
ps.setString(3, settingsMap.get("SPECIALNUMBER"));
ps.setString(4, settingsMap.get("USERNAME"));
ps.setString(5, passwdConvert(settingsMap.get("PASSWD")));
ps.setDate(6, toDate(settingsMap.get("DATETOCHANGEPASSWD")));
ps.setString(7, settingsMap.get("ADDRESS"));
ps.setString(8, settingsMap.get("STATEREGION"));
ps.setString(9, settingsMap.get("COUNTRY"));
ps.setString(10, settingsMap.get("USERSTATUS"));
ps.setString(11, settingsMap.get("TELEPHONE"));
ps.setDate(12, toDate(settingsMap.get("DATEUSERADDED")));
ps.setDate(13, toDate(settingsMap.get("USEREXPIREDATE")));
ps.setDate(14, toDate(settingsMap.get("DATEUSERLOCKED")));
ps.setString(15, settingsMap.get("CITY"));
ps.setString(16, settingsMap.get("EMAIL"));
ps.setString(17, settingsMap.get("DESCRIPTION"));
ps.executeUpdate();
conn.commit();
committed = true;
}
finally
{
if (!committed) {
conn.rollback();
}
}
} finally {
/* Release the resources */
ps.close();
conn.close();
}
return result;
}
Right now I cannot test the SQL query. Can you tell me is it valid and how I can optimize the SQL query for performance?
Right now I cannot test the SQL query. Can you tell me is it valid ...
Not with any certainty. (Why don't you wait until you CAN test it??)
... and how I can optimize the SQL query for performance?
It is not entirely clear what you are trying to do. However, here are some suggestions on performance:
You are creating and releasing a database connection for each SQL statement executed. That has to be bad for performance.
There is no need to do an insert followed by an update of the same record ... if that is what you are proposing to do.
You will get performance by doing a bulk or batch insert or update rather than inserting records one at a time.
If you are inserting lots of data into an empty table with lots of indexes, then you may get better performance if you do the insertions first and create the indexes afterwards.
At the level of a single query (i.e. the "UPDATE"), you probably cannot make the query significantly faster.
The only improvement you can make is put the id as '?' also:
UPDATE USERS "
+ "SET "
+ "USERID = ?, "
+ "GROUPID = ?, "
+ "SPECIALNUMBER = ?, "
+ "USERNAME = ?, "
+ "PASSWD = ?, "
+ "DATETOCHANGEPASSWD = ?, "
+ "ADDRESS = ?, "
+ "STATEREGION = ?, "
+ "COUNTRY = ?, "
+ "USERSTATUS = ?, "
+ "TELEPHONE = ?, "
+ "DATEUSERADDED = ?, "
+ "USEREXPIREDATE = ?, "
+ "DATEUSERLOCKED = ?, "
+ "CITY = ?, "
+ "EMAIL = ?, "
+ "DESCRIPTION = ? "
+ "WHERE USERID = ?";
And of course add a set decleration:
ps.setInt(18, id);
I think there is nothing to optimize because you are inserting to only one table. Same for update. There are no joins or grouping so there is really anything you can do about it. Maybe just one note - you could use StringBuilder for code formatting :-)
If you are going to insert several rows, then you could increase performance by reusing the database connection, as well as the prepared statement. The latter requires treating the user id as a row as well, the way ftom2 suggested. Apart from that, there is little room for performance optimizations.

Categories

Resources