简体   繁体   中英

Best practices to Minimize/Manage SQL string blobs in data access code (e.g. Dapper)

I've built some data layers using Dapper with great pleasure. Of course maintaining the required SQL strings can be an issue, especially when the db schema changes (rename column etc).

I'm looking for a strategy to "remove" most SQL string blobs (without using EF or Linq). Either find/build a type safe query API to generate SQL (like jooq) or some kind of meta generation comes to mind.

Am I missing anything? Is there a best practice or better approach?

Thank you

Note: Using EF or Linq would solve the issue but we're striving to be as close to SQL as possible.

I totally agree with John Wu. Stored procedures are the way to go here.
You can think of stored procedures as a way to encapsulate your database - your application doesn't need to know how the data is stored, it only needs to know what stored procedures are available and what they do.

There are plenty of benefits:

  1. This keeps your SQL statements out of the application code.
  2. Your queries are compiled and re-used in the database, so you gain performance.
  3. Your SQL Login can have a more restrictive security details, making it harder for hackers to damage your database.
  4. Stored procedures almost eliminate the chance of SQL Injection (Unless you are using dynamic SQL inside), since you must use parameters to pass data to the stored procedure.
  5. Some changes in the database structure can be made without the need to re-compile your software, since it no longer access the tables directly.
  6. A lot of SQL code can be done more efficiently with stored procedures (for instance, Inline sql can't use table valued parameters)
  7. using stored procedures can make your life easier if you need to support multiple database vendors - for instance, the differences between pl/sql and t-sql are no longer an issue.

I'm sure that there are plenty of reasons I didn't cover, as well as there are some reasons against working with stored procedures. (For instance, one might say that stored procedures allows you to move logic to the database, and that's the wrong place to put logic in. I personally disagree with this statement - I think some logic MUST be in the database.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM