Why am I getting java.sql.SQLException: Operation not allowed after ResultSet closed - resultset

So I've been looking around about this problem and it seems that the problem arises when a statement tries to get multiple ResultSets.
But in the following code I get the exception, even though the executeUpdate just returns an int.
ResultSet resultsRS = statement.executeQuery("select distinct snum from shipments where quantity >= 100");
int rowCount=0;
while(resultsRS.next()){
statement.executeUpdate("UPDATE suppliers SET status = status + 5 WHERE snum = "+"\""+resultsRS.getString(1)+"\"");
rowCount++;
}
It runs one time fine, after that it gives the exception.
How would I be able to fix this?

All execution methods in the Statement interface implicitly close a statment's current ResultSet. See docs So you need to store resultSet data in a temporary array and loop through it.
Or try to use another statement for executeUpdate.
Try something like this:
ArrayList<String> tmp = new ArrayList<String>();
while(resultsRS.next()){
tmp.add(resultsRS.getString(1));
}
for (String s: tmp) {
statement.executeUpdate("UPDATE suppliers SET status = status + 5 WHERE snum = "+"\""+s+"\"");
rowCount++;
}

Related

Postgres: How to update the column?

I use the postgres library to work with the database. I have a very large database. I need to change the character in the column. I do it like this:
void replace(String col, String from, String to) async {
String queryStr = "UPDATE $tab SET $col = replace($col, '$from', '$to');";
await connection.query(queryStr);
}
If the database has more than 1,000,000 rows, I get an error:
Unhandled exception: TimeoutException after 0:00:30.000000: Future not
completed
0 _PostgreSQLConnection&Object&_PostgreSQLExecutionContextMixin._enqueue (package:postgres/src/connection.dart:402:24)
1 _PostgreSQLConnection&Object&_PostgreSQLExecutionContextMixin.query (package:postgres/src/connection.dart:318:12)
2 PG.replace (file:///home/vas/IdeaProjects/infovizion_platform/pg/bin/pg.dart:50:22)
3 main (file:///home/vas/IdeaProjects/infovizion_platform/pg/bin/main.dart:81:14)
4 _startIsolate. (dart:isolate/runtime/libisolate_patch.dart:287:32)
5 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
When I do the same requests manually there is no error.
How can I fix this?
You might try this version:
UPDATE $tab
SET $col = replace($col, '$from', '$to')
WHERE $col LIKE '%' || '$from' || '%';
That is, only update columns where the value actually appears, instead of all column.
Reducing the number of columns that actually change may speed the query.

Linq Query in VB

Good Day,
I am querying my database using Linq and I have run into a problem, the query searched a column for a search phrase and based on if the column has the phrase, it then returns the results, The query is below,
Dim pdb = New ProductDataContext()
Dim query =
From a In pdb.tblUSSeries
Join b In pdb.tblSizes_ On a.Series Equals b.Series
Where
a.Series.ToString().Equals(searchString) Or
b.Description.Contains(searchString) Or Not b.Description.Contains(Nothing)
Order By b.Series, b.OrderCode Ascending
Select New CustomSearch With
{
.Series = a.Series,
.SeriesDescription= a.Description,
.Coolant = a.Coolant,
.Material = a.Material,
.Standard = a.Standard,
.Surface = a.Surface,
.Type = a.Type,
.PointAngle = a.PointAngle,
.DiaRange = a.DiaRange,
.Shank = b.Shank,
.Flutes = b.Flutes,
.EDPNum = b.EDPNum,
.SizesDescription = b.Description,
.OrderCode = b.OrderCode
}
Return query
I think the problem is that, in the table certain rows are NULL, so when it is checking the column for the phrase and it encounters a row that is null it, breaks and returns this error,
The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
I have ran this query against another column that has all the rows populated with data and it returns the results ok.
So my question is how can I write it in VB to query the db with the supplied searchstring and return the results, when some of the rows in the columns have null values.
Any help would be great.
The exception occurs when you make the projection (i.e. select new CustomSearch)
And yes your trying to assign Null to some int property
(Not sure which one of your properties that is)
one of 2 choices :
1) Use nullalbe types for your properties (or just that one property).
2) project with an inline If ( ?? in C#) , I don't know VB so don't catch me on the syntax.
Taking Series just as an example i don't know if it's an int or if that's the problematic property
Select New CustomSearch With
{
.Series = If(a.Series Is Nothing,0, CInt(a.Series))
}
In C#
Select new CustomSearch
{
Series = a.Series ?? 0;
}

TAG= 'Token line number = 1,Token line offset = 29,Token in error = FROM ' ... insert data from one column to another column of other table

Well... I have two tables named : "chefs" and "cust_Data".
I want to :
Put comments from cust_Data that are being posted into the comment column in chefs table.
By being posted means-> M giving a comment section so that customers will put their comments in "comment" column in "cust_Data" and as soon as those comments are in cust_Data...
Put those comment in "comments" column in "chefs" table.
RAZOR CODE:
#{
var db = Database.Open("vendors");
var selectCommand = "SELECT dish FROM chefs WHERE ID= #0";
var chefID = Request.QueryString["chefid"];
var selectedData = db.Query(selectCommand, chefID);
var dishName=Request.QueryString["dish"];
var chefName=Request.QueryString["chefName"];
var comments=Request["SELECT comments from chefs"]; //IMPORTANT
var ID=Request["SELECT ID from chefs"]; //IMPORTANT
var grid = new WebGrid(source: selectedData, rowsPerPage: 10);
Validation.RequireField("cust_fname", "You must enter your firstname");
Validation.RequireField("cust_lname", "You must enter your surname");
Validation.RequireField("cust_email", "You haven't entered a valid Email_ID");
Validation.RequireField("rating", "Rating is required");
Validation.RequireField("comment", "Please provide your Comment about Respective Homeschef");
var cust_fname = "";
var cust_lname= "";
var cust_email= "";
var rating= "";
var comment= ""; //IMPORTANT
if(IsPost && Validation.IsValid() && chefID.AsInt()!=0){
cust_fname = Request.Form["cust_fname"];
cust_lname = Request.Form["cust_lname"];
cust_email = Request.Form["cust_email"];
rating = Request.Form["rating"];
comment = Request.Form["comment"]; // IMPORTANT->TAKING COMMENT FROM USER
var insertCommand = "INSERT INTO cust_Data (cust_fname, cust_lname, cust_email, dish, chef_ID, rating, comment) Values(#0, #1, #2, #3, #4, #5, #6)";
db.Execute(insertCommand,cust_fname,cust_lname, cust_email, dishName, chefID, rating, comment); // EXECUTED SUCCESSFULLY IN cust_Data
var insert= "INSERT INTO chefs(comments) FROM cust_Data(comment) WHERE chefs(ID)=cust_Data(chef_ID) Values(#0,#1,#2,#3)"; //IMPORTANT
db.Execute(insert,comments,comment,ID,chefID); // IMPORTANT -> ERROR OCCURED ?????????
}
}
Exception Details: System.Data.SqlServerCe.SqlCeException: There was an error parsing the query. [ Token line number = 1,Token line offset = 29,Token in error = FROM ]
I inserted IMPORTANT TAG(to save your time for important things) from where i took the parameters I needed to parse.
Again, Thank you so much in advance...
Though this is not a complete answer, writing this as a answer as the content for explanation is too long.
Even though you've updated the insert into command, the select statement is still wrong. You are trying to write the select statement using the syntax of insert statement i.e. table_name(column_name) but it should be
SELECT column_name from table_name WHERE table_name.column_name=''
Insert into statement works by taking complete SQL select statement prefixed by Insert Into clause. So, your code should be something like this:
INSERT INTO chefs(comments) SELECT comments from cust_Data WHERE chefs.ID=cust_Data.chef_ID
But this won't work as you've not joined the table chefs and cust_data. So you will have to join both the tables and get the correct records, then use the insert into command to insert the records into the chefs table.
Looking more into your program, it looks like you want to update the existing records from the chefs table, or insert is the correct one? Your chefs table has other columns i.e. ID,dish which have been ignored in the insert statement. I doubt that this insert statement would run properly without these columns.
Also, why are you querying comments and ID values separately. And the rows are also not filtered, so it will fetch all the records from the database.
var comments=Request["SELECT comments from chefs"]; //IMPORTANT
var ID=Request["SELECT ID from chefs"]; //IMPORTANT
The database structure and your agenda that you are trying to achieve looks weird to me. I.e. Customer enters the data in cust_data.comments and you want to move/copy these comments to chefs.comment and as soon as the data comes in cust_data table. Why not directly insert into the chefs table instead of this 2 step approach.
Have you thought about the whole process from start to finish? Have you drawn it on paper or screen using UML diagram/process flow?
It looks like you do not have enough experience on the database side. My suggestion would be that you first try these statements directly on the database tool SSMS, get it confirmed that it's working and then apply it in your program. You can use hard coded values for testing and then substitute with parameters when applying it into the program.
Also it would help you if you can learn Stored Procedures and use that in your program. This will reduce such complications from program side and also reduce the database calls

Hibernate createSQLQuery and Toad SQL query return different results - parameter problems?

I'm a newbie at Hibernate so excuse me if some of this is glaringly obvious but it's been a very, very long day. I am trying to create and execute a simple query in Hibernate and Toad/Oracle.
The Toad/Oracle sql reads:
select
count(*)
from
fpps_owner.fee_claim_payment_lines l,
fpps_owner.fee_claim_payments p
where
l.fee_claim_payment_id = p.fee_claim_payment_id and
p.claim_index = 87167895
The above returns 10 records, which is correct
The following Java code returns 0 records, which is NOT correct
String sLinesAvailable =
"select count(*) from " +
"fpps_owner.fee_claim_payment_lines l, fpps_owner.fee_claim_payments p " +
"where " +
"l.fee_claim_payment_id = p.fee_claim_payment_id and p.claim_index = :id";
Query qLinesAvailable = em.createNativeQuery(sLinesAvailable);
qLinesAvailable.setParameter("id", "87167895"); // fails
qLinesAvailable.setParameter("id", 87167895); // fails
List<Object> out = (List<Object>) qLinesAvailable.getResultList();
BigDecimal x = (BigDecimal) out.get(0);
Returns 0 records. Using .getSingleResult() also returns 0 records.
What am I missing here?
Any help would be GREATLY appreciated!
If you are not seeing any malformed query errors, it seems like the parameter is not binding correctly.
To debug, I'd print out that SQL statement the line after you set the parameter. This is the only way you can see the SQL after the parameter is set in order to compare it with Toad.
What does your binding file look like? Maybe you have a different name in there for the ID, so it's not able to find it based on the name. Trying binding with the parameter's order value, just as a test.
This might give some ideas: http://www.mkyong.com/hibernate/hibernate-parameter-binding-examples/
Best of luck! We've all been there :)
What happens when you try:
(Number) query.getSingleResult();
Your query isn't returning a list, but rather just a count.
Good luck.

django using .extra() got error `only a single result allowed for a SELECT that is part of an expression`

I'm trying to use .extra() where the query return more than 1 result, like :
'SELECT "books_books"."*" FROM "books_books" WHERE "books_books"."owner_id" = %s' % request.user.id
I got an error : only a single result allowed for a SELECT that is part of an expression
Try it on dev-server using sqlite3. Anybody knows how to fix this? Or my query is wrong?
EDIT:
I'm using django-simple-ratings, my model like this :
class Thread(models.Model):
#
#
ratings = Ratings()
I want to display each Thread's ratings and whether a user already rated it or not. For 2 items, it will hit 6 times, 1 for the actual Thread and 2 for accessing the ratings. The query:
threads = Thread.ratings.order_by_rating().filter(section = section)\
.select_related('creator')\
.prefetch_related('replies')
threads = threads.extra(select = dict(myratings = "SELECT SUM('section_threadrating'.'score') AS 'agg' FROM 'section_threadrating' WHERE 'section_threadrating'.'content_object_id' = 'section_thread'.'id' ",)
Then i can print each Thread's ratings without hitting the db more. For the 2nd query, i add :
#continue from extra
blahblah.extra(select = dict(myratings = '#####code above####',
voter_id = "SELECT 'section_threadrating'.'user_id' FROM 'section_threadrating' WHERE ('section_threadrating'.'content_object_id' = 'section_thread'.'id' AND 'section_threadrating'.'user_id' = '3') "))
Hard-coded the user_id. Then when i use it on template like this :
{% ifequal threads.voter_id user.id %}
#the rest of the code
I got an error : only a single result allowed for a SELECT that is part of an expression
Let me know if it's not clear enough.
The problem is in the query. Generally, when you are writing subqueries, they must return only 1 result. So a subquery like the one voter_id:
select ..., (select sectio_threadrating.user_id from ...) as voter_id from ....
is invalid, because it can return more than one result. If you are sure it will always return one result, you can use the max() or min() aggregation function:
blahblah.extra(select = dict(myratings = '#####code above####',
voter_id = "SELECT max('section_threadrating'.'user_id') FROM 'section_threadrating' WHERE ('section_threadrating'.'content_object_id' = 'section_thread'.'id' AND 'section_threadrating'.'user_id' = '3') "))
This will make the subquery always return 1 result.
Removing that hard-code, what user_id are you expecting to retrieve here? Maybe you just can't reduce to 1 user using only SQL.