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);
Related
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'm trying to connect my project with an SQL-Server database. But I always get this error E/ERROR: The executeQuery method must return a result set.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES ('" + informacao.getNomeCliente() + "', '" + informacao.getNome() + "', '" + informacao.getEmail() + "', '" + informacao.getSatisfacao() + "', '" + informacao.getNota() + "') ";
Statement stmt = conn.createStatement();
ResultSet rSet = stmt.executeQuery(sql); // error here
I tried to change stmt.executeQuery to stmt.executeUpdate, but it underlines it red, and says that the output is int, so it is incompatible.
Using PreparedStatement is much safer.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, informacao.getNomeCliente())
pstmt.setString(2, informacao.getNome())
pstmt.setString(3, informacao.getEmail())
pstmt.setString(4, informacao.getSatisfacao())
pstmt.setString(5, informacao.getNota())
int result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
I think you should use the executeQuery method while querying tables in the database (when you have the SELECT keyword). When you want to execute SQL statements (like INSERT, UPDATE and others) you should use execute method, as seen in here.
In your case you could try:
Boolean rSet = stmt.execute(sql);
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 trying to figure out why this code is throwing an SQL exception. When I run this code it prints "Bad SQL in customer insert ps", which is the message in that inner catch block. I've got multiple prepared statements with SQL inserts like this both in this class and also elsewhere in my application. They're all working fine. I've looked through this one over and over again, and I can't figure out why this one is throwing an exception.
try {
Connection conn = DBconnection.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";");
System.out.println(ps.toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customerId = rs.getString("customerId");
}
try {
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT "
+ "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)"
+ "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");");
customerInsert.executeUpdate();
System.out.println(customerInsert.toString());
System.out.println(rs.toString());
} catch (SQLException sq) {
System.out.println("Bad SQL in customer insert ps");
}
} catch (SQLException customerIdException) {
System.out.println("Bad SQL in customer ps");
}
You're using PreparedStatement as though you were using Statement. Don't put the parameters in the SQL, put in placeholder ? marks. Then use the various setXyz methods (setString, setInt, etc.) to fill in the parameters:
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
"INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(?, ?, ?, ?, ?, ?, ?);"
);
customerInsert.setString(1, name);
customerInsert.setInt(2, addressId);
// ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect
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.