I'm using Go and Gorm for Postgresql.
I want to understand what the difference is between
this:
var name = "myName" var user User db.Where("user like ?", name).Find(&user)
and this:
var user User db.Where("user like " + name).Find(&user)
The SQL query is the same.
I mean, why do we use ORMs?
Can the #1 become a prepared statement?
Is the #1 "more optimized" than the #2?
What does it mean "more optimized"?
To answer specifically to your questions:
Can the #1 become a prepared statement?
Usually ORMs will build prepared statements, so that (as explained by Flimzy) you can avoid sql injection and DB engine does not need to recalculate query plans.
Gorm seems to have an specific configuration for caching prepared statements: https://gorm.io/docs/v2_release_note.html#Prepared-Statement-Mode
Is the #1 "more optimized" than the #2?
You can see this part from database perspective and language perspective.
"user like"
, then another string for the concatenation"user like" + name
. If this code is executed multiple times (in a loop for example) you will see an increase of execution time, just because each string means a new memory address assigned.What does it mean "more optimized"?
More optimized means faster. As explained above: