Hello this looks like simple but I am having issues here.
Firstly I am using Statement#executeBatch for executing many UPDATE statements. Each update statements have String value to be updated. These String have " ' " single quote. I have tried adding one more single quote in front of it as per Oracle doc as well adding '\\\' in front of single quote. With the first one, my query gets stuck and does not come out even after 10 minutes. With second one I get 'batching: ORA-00927: missing equal sign' error.
What is the correct approach?
Note:- I cannot use PreparedStatement to make use of JDBC parameters.
Please help.
You may use the q-quoted string eg q'['''''''']'
This give a following example
Statement stmt = con.createStatement();
stmt.addBatch("update tst set txt = q'['''''''']' where id = 1");
stmt.addBatch("update tst set txt = q'['''''''']' where id = 2");
stmt.addBatch("update tst set txt = q'['''''''']' where id = 3");
stmt.addBatch("update tst set txt = q'['''''''']' where id = 4");
stmt.addBatch("update tst set txt = q'['''''''']' where id = 5");
// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();
But the correct way is to use the prepared statement
PreparedStatement stmt = con.prepareStatement("update tst set txt = ? where id = ?");
5.times { i ->
stmt.setString(1, "''''''''");
stmt.setInt(2, i+1);
stmt.addBatch();
}
// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();
Related
i'm working in java with sql.when ever this query is executed it gives me the error mentioned in title
try(PreparedStatement statement = conn.prepareStatement("INSERT INTO student_signup(q" + strId + ")" + "WHERE student_email="+email+"VALUES(?)")) {
statement.setString(1, SelectedOption);
statement.executeUpdate();
statement.close();
for a little code background
here
int questionID=1;
String strId = Integer.toString(questionID);
String email = signInForm.getTxtEmail().getText();
INSERT inserts new rows. I think you want to change a value in an existing row. For that, use UPDATE. Something like this:
UPDATE student_signup
SET strID = ?
WHERE student_email = ?;
INSERT is never use with WHERE clause
If you want to change the value for a pre-existing record in the database, you should try the UPDATE clause with WHERE condition after it.
I have a requirement to create a temp table and select on the temp table against Netezza DB in one session.
Tables: abc, def
String query = create temp table MyTemp as select * from abc join def; select col1, col2 from MyTemp;";
boolean result = statement.execute(query);
while(true) {
if(result) {
ResultSet rs = statements.getResultSet();
while(rs.next()) {
//Access result set.
}
} else {
int count = statement.getUpdateCount(); -- CREATE statement output
if(count == -1) {
break;
}
result = statement.getMoreResults();
}
}
I expected to get the updatecount and then a resultset from the statement as I am executing CREATE temp statement followed by SELECT statement.
I get result as true for the first statement(CREATE statement output). But later when statement.getMoreResults gets executed I get false. But according to documentation the statement.getMoreResults returns true for ResultSet output.
I have an alternative solution of splitting the string using semicolon and executing the individual queries using the same statement. But I want to know why the above solution doesn't work.
I'm unsure as to whether the Netezza JDBC driver supports it, or if it will even work with your example queries and existing code, but it looks like you may need to pass allowMultiQueries=true as an option for your JDBC URL.
See this answer for more information.
I have an assignment where I need to update records using a PreparedStatement. Once the record have been updated as we know update query return count, i.e., number of row affected.
However, instead of the count I want the rows that were affected by update query in response, or at least a list of id values for the rows that were affected.
This my update query.
UPDATE User_Information uInfo SET address = uInfo.contact_number || uInfo.address where uInfo.user_id between ? AND ?;
Normally it will return count of row affected but in my case query should return the ids of row or all the row affected.
I have used the returning function of PostgreSQL it is working but is not useful for me in that case.
i have used returning function of PostgreSQL but is not useful for me
It should be. Perhaps you were just using it wrong. This code works for me:
sql = "UPDATE table1 SET customer = customer || 'X' WHERE customer LIKE 'ba%' RETURNING id";
try (PreparedStatement s = conn.prepareStatement(sql)) {
s.execute(); // perform the UPDATE
try (ResultSet rs = s.getResultSet()) {
// loop through rows from the RETURNING clause
while (rs.next()) {
System.out.println(rs.getInt("id")); // print the "id" value of the updated row
}
}
}
The documentation indicates that we can also use RETURNING * if we want the ResultSet to include the entire updated row.
Update:
As #CraigRinger suggests in his comment, the PostgreSQL JDBC driver does actually support .getGeneratedKeys() for UPDATE statements too, so this code worked for me as well:
sql = "UPDATE table1 SET customer = customer || 'X' WHERE customer LIKE 'ba%'";
try (PreparedStatement s = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
s.execute(); // perform the UPDATE
try (ResultSet rs = s.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1)); // print the "id" value of the updated row
}
}
}
Thanks, Craig!
You might be able to use JDBC's support for getting generated keys. See the Connection.prepareStatement(String sql, int[] columnIndexes) API method, then use Statement.getGeneratedKeys() to access the results.
The spec says "the driver will ignore the array if the SQL statement is not an INSERT statement" but I think PostgreSQL's JDBC driver will actually honour your request with other statement types too.
e.g.
PreparedStatement s = conn.prepareStatement(sql, new String[] {'id'})
s.executeUpdate();
ResultSet rs = s.getGeneratedKeys();
Otherwise, use RETURNING, as Gord Thompson describes.
There are two way of doing it
1. by passing an array of column name or index of column prepareStatement
i.e conn.prepareStatement(sql, new String[] {'id','uname'})
and
2. by using Statement.RETURN_GENERATED_KEYS in prepareStatement.
My code is for this i.e as per my requirement i have developed my code you can have a look for better idea.
private static final String UPDATE_USER_QUERY= "UPDATE User_Information uInfo SET address = uInfo.contact_number || uInfo.address where uInfo.user_id between ? AND ?;";
//pst = connection.prepareStatement(UPDATE_USER_QUERY,columnNames);
pst = connection.prepareStatement(UPDATE_USER_QUERY,Statement.RETURN_GENERATED_KEYS);
ResultSet rst = pst.getGeneratedKeys();
List<UserInformation> userInformationList = new ArrayList<UserInformation>();
UserInformation userInformation;
while (rst.next()){
userInformation = new UserInformation();
userInformation.setUserId(rst.getLong("user_id"));
userInformation.setUserName(rst.getString("user_name"));
userInformation.setUserLName(rst.getString("user_lName"));
userInformation.setAddress(rst.getString("address"));
userInformation.setContactNumber(rst.getLong("contact_number"));
userInformationList.add(userInformation);
}
That think i need to achieve in this case.
Hope so this will help you a lot.
I have a table in mysql that contain a field called template.
I have one template stored in a variable, I need to compare that variable with each of the other templates found in the table until a match is found. I dont know how to retrieve one template from the database row at a time, compare it and if it does not match, move to next row to compare again and so on until match is found. I am new to mysql looping, please help.
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
PreparedStatement st;
st = con.prepareStatement("select template from tbl1 ");
ResultSet result = st.executeQuery();
while (result.next()) {
String dbTemplate = result.getString("template");
if x == dbtemplate
} else {// move to next row? How to say do the loop for next row in table??
}
Ask SQL to check it for you, Try this:
st = con.prepareStatement("select template from tbl1 where template = ?");
st.setString(1, "template_name");
Then you would only have results that templates matches
result.next() any way gets next row. All you need to do would do condition check inside and if condition satisfied, then only execute the functionality you want.
while (result.next()) {
if(yourConditionSatisfied) {
//All your logic goes here. If you want to break the lookup, just add break here.
}
}
This is java program for SQL statement. I have two queries. Result of the first query is required for second query.
How do I call it in second query?
These results are values for xml tags.
I need to get first query result for this tag
child1.setAttributeNS(xlink,"xlink:type","");
but this is located in 2nd query and if i try to merge those 2 query I get eror resultset closed.
while(rs1.next()){
int i=0,j=0 ,locid,supid;
int lc[]=new int[100];
int sp[]=new int[100];
lc[i] = rs1.getInt(2);
sp[j] = rs1.getInt(1);
lcid=lc[i++];*/
for(i=0;i<loc[i];i++){
for(j=0;j<sup[j];j++){
lcid=lc[i]; spid=sp[j];
System.out.print(spid +" ");
System.out.println(lcid);
String s = (lc[i]==1 ? "simple" : (lc[i]>1 ? "extended" : null));
System.out.println(s); }}}
String querystring=
" ";
rs = stmt.executeQuery(querystring );
while(rs.next()){
Element child1 = doc.createElement("slink");
/
Element element = doc.createElement("loc");
You need to create a brand new and separate Statement for the second ResultSet. Everytime you get a new ResultSet out of a single Statement, every previously opened one will namely be closed.
Replace
rs = stmt.executeQuery(querystring );
by
Statement stmt2 = connection.createStatement();
rs = stmt2.executeQuery(querystring);
Don't forget to add stmt2.close() to the finally block.
Unrelated to the concrete problem, have you considered just JOINing the both queries and using Javabeans to represent the model? This way you end up with a single query and more self-documenting code.