Is Query.Close necessary after Query.ExecSQL? - delphi

In Delphi, whenever I use a TQuery to perform a SELECT on a database, I follow the Query.Open with a try..finally, with Query.Close in the finally section. This makes sense to me, as the Query would still be storing data (using memory) unnecessarily otherwise.
But my question has to do with when I use a Query to perform an INSERT or DELETE, thus requiring the execution of the SQL with Query.ExecSQL
My question is, must I use Query.Close after Query.ExecSQL?
My thoughts are, because this is a command to be executed on the database, which presumably does not return any data to the Query, there is no need to do a Query.Close
But maybe someone out there has more in-depth knowledge of what, if anything, might be returned and stored in a Query after a Query.ExecSQL is called, for which a Query.Close would be beneficial?
Thank you.

No it is not needed as ExecSQL does not maintain a recordset.
from the documentation (emphasis mine):
Executes the SQL statement for the query. Call ExecSQL to execute the
SQL statement currently assigned to the SQL property. Use ExecSQL to
execute queries that do not return a cursor to data (such as INSERT,
UPDATE, DELETE, and CREATE TABLE).
Note: For SELECT statements, call Open instead of ExecSQL.
ExecSQL prepares the statement in SQL property for execution if it has not already been prepared. To speed performance, an application should ordinarily call Prepare before calling ExecSQL for the first time.

Related

Why NHibernate not reflecting in-memory state when updates made with stored procedure?

I have a process whereby I have an NHibernate session which I use to run a query against the database. I then iterate through the collection of results, and for each iteration, using the same NHibernate session, I call a SQL Stored Procedure (using CreateSQLQuery() & ExecuteUpdate()), which ends up performing an update on a field for that entity.
When it has finished iterating over the list (and calling the SP x times), if I check the database directly in SSMS, I can see that the UPDATE for each row has been applied.
However, in my code, if I then immediately run the same initial query again, to retrieve that list of entities, it does not reflect the updates that the SP made for each row - the value is still NULL.
I haven't got any cache behavior specified against the configuration of NHibernate in my application, and have experimented with different SetCacheMode() when calling the query, but nothing seems to make any difference - the values that I can see directly in the DB have been updated, are not being brought back as updated when I re-query (using Session.QueryOver()) the database (using that same session).
By calling CreateSQLQuery (to update database, single row or multiple rows does not matter), actually you are doing DML-style operation which does not update the in-memory state.
Any call to CreateSQLQuery or CreateQuery will not use/reflect tracking. These are considered out-of-the-scope of Unit Of Work.
These operations directly affect the underlying database neglecting any in-memory state.
14.3. DML-style operations
As already discussed, automatic and transparent object/relational mapping is concerned with the management of object state. This implies that the object state is available in memory, hence manipulating (using the SQL Data Manipulation Language (DML) statements: INSERT, UPDATE, DELETE) data directly in the database will not affect in-memory state. However, NHibernate provides methods for bulk SQL-style DML statement execution which are performed through the Hibernate Query Language (HQL). A Linq implementation is available too.
They (may) work on bulk data. They are necessary in some scenarios for performance reasons. With these, tracking does not work; so yes, in-memory state become invalid. You have to use them carefully.
if I then immediately run the same initial query again, to retrieve that list of entities, it does not reflect the updates that the SP made for each row - the value is still NULL.
This is due to first (session) level cache. This is always enabled by default and cannot be disabled with ISession.
When you first load the objects, its a database hit. You get the objects from database - loop through them - execute commands those are out of Unit Of Work (as explained above) - and again execute same query twice to load same objects under same ISession instance. Second call does not hit the database at all.
It just return the instances from memory. As your in-memory instances are not updated at all, you always get original instances.
To get the updated instances, close the first session and reload the instances with new session.
For more details, please refer to: How does Hibernate Query Cache work

Mvc: The use of IQueryable and Asqueryable is not clear

I found some lines of code online and I understand the first two lines. Data of a particular
type is cached and stored in the two properties of the models below.
model.payment = (List<CompInfor>)HttpRuntime.Cache[cacheKey + "_received"];
model.FilteredPayment = (List<CompInfor>)HttpRuntime.Cache[cacheKey + "_received"];
However I don't understand the line below as I have never written code like this below.
Please what does this line do? What does it mean? I know you can save a lot of resources by using IQueryable.
IQueryable<CompInfor> payment = model.FilteredPayment.AsQueryable<CompInfor>();
It simply returns an instance of the IQueryable<T> interface which will utilize a query provider to act upon the object in question (in your case, the model.FilteredPayment list). It doesn't seem to make much sense when you're acting against a List locally, but (as an example) in the case of entity framework where you build query statement to be executed against a database via SQL, the Linq to Entities query provider processes the IQueryable into the appropriate SQL statement for execution against the database and processes the results.

What is the fastest way to get any object JSON from the database to the client without leaving behind opportunities for SQL injection?

What is the fastest way to get JSON from the database to the client without leaving behind opportunities for SQL injection?
I am looking at paging, insert, update, delete, sort, etc... against any table in my schema.
This all depends on what data you are querying.
The fact you are using JSON doesnt have anything to do with sql injection - its more of the calls to the database that would be a concern.
On the server side do not form any dynamic sql.
1. Use stored procedures (and do not include any dynamic sql in a stored proc - if you do make sure you use sp_executesql and not exec, as sp_executesql can take a parameterized query 2. use parameterized queries
3. use an ORM (ex. entity framework) which uses parameterized queries behind the scenes anyways.
try not to use any dynamic sql - if you must for some reason then make sure you use parameterized queries.
then on your result from your controller simply return
return Json(yourModel);

How to update a single field using EF4

I want to update a single field in my table for a particular row. I am using Entity Framework 4 and Visual Studio 2010.
Options I can think of are:
Using a Stored Procedure
Direct connection to the database and using
sql statement
I am not aware of any more efficient method to perform this task.
[EDIT]
I would like to do the update in the same operation as the Get for that row, so that it is done in one DB call.
No need to complicate things. Just change the one property and SaveChanges. Unless you're doing something odd, that should only change the one column. Look at the SQL to verify.

linq: SQL performance on high loaded web applications

I started working with linq to SQL several weeks ago. I got really tired of working with SQL server directly through the SQL queries (sqldatareader, sqlcommand and all this good stuff). 
After hearing about linq to SQL and mvc I quickly moved all my projects to these technologies. I expected linq to SQL work slower but it suprisongly turned out to be pretty fast, primarily because I always forgot to close my connections when using datareaders. Now I don't have to worry about it.
But there's one problem that really bothers me. There's one page that's requested thousands of times a day. The system gets data in the beginning, works with it and updates it. Primarily the updates are ++ # -- (increase and decrease values). I used to do it like this
UPDATE table SET value=value+1 WHERE ID=#I'd
It worked with no problems obviously. But with linq to SQL the data is taken in the beginning, moved to the class, changed and then saved.
Stats.registeredusers++;
Db.submitchanges();
Let's say there were 100 000 users. Linq will say "let it be 100 001" instead of "let it be increased by 1".
But if there value of users has already been increased (that happens in my site all the time) then linq will be like oops, this value is already 100 001. Whatever I'll throw an exception"
You can change this behavior so that it won't throw an exception but it still will not set the value to 100 002.
Like I said, it happened with me all the time. The stas value was increased twice a second on average. I simply had to rewrite this chunk of code with classic ado net.
So my question is how can you solve the problem with linq
For these types of "write-only queries" I usually use a Stored Procedure. You can drag the stored procedure into the designer and execute it through the Linq to SQL DataContext class (it will be added as a method).
Sorry for the trite answer but it really is that simple; no need to to finagle with raw ADO.NET SqlCommand objects and the like, just import the SP and you're done. Or, if you want to go really ad-hoc, use the ExecuteCommand method, as in:
context.ExecuteCommand("UPDATE table SET value = value + 1 WHERE ID = {0}", id);
(But don't overuse this, it can get difficult to maintain since the logic is no longer contained in your DataContext instance. And before anybody jumps on this claiming it to be a SQL injection vulnerability, please note that ExecuteCommand/ExecuteQuery are smart methods that turn this into a parameterized statement/query.)
Linq to Sql supports "optimistic" concurrency out of the box. If you need tighter control, you can add a Timestamp column to your table, and Linq to Sql will use that timestamp to tighten the concurrency.
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/07/01/10557.aspx
However, as Morten points out in the comments below, this solution is not going to perform well. Of course, you can always use ADO.NET to update the value, just like you were doing before; that won't adversely affect the operation of your Linq queries at all.
You could turn off concurrency on that property by changing the UpdateCheck value:
http://msdn.microsoft.com/en-us/library/bb399394(v=VS.90).aspx
Messy if your using generated code and the designer but I think this is the only way to do this.

Resources