What is the best strategy to avoid hard coded SQL statements

后端 未结 5 670
悲哀的现实
悲哀的现实 2021-01-23 02:00

The other day I was showing a colleague some code I was working on, and in the passing he commented on the fact that I have hard coded SQL statements. Now these SQL Statements a

相关标签:
5条回答
  • 2021-01-23 02:45

    It really depends on your data model and what permissions you have to the database. I've been to companies who do not allow their .Net developers to write Stored Procs and only allow a select group of database developers to do such.

    Like Frakkle mentioned, if your data model doesn't change often, then most likely the hard coded statements won't be a problem.

    There are ways to parametrize your hard coded sql statements if you don't use Stored Procedures or an ORM tool. This is a recommended practice.

    If you are using MSSql 2005+ then, from what I've seen and tested, your hard coded statements will have their execution plans still cached. There are also hints that can be used (like OPTIMIZE FOR UNKNOWN) that will help it out the performance even more.

    Evaluate your environment and the amount of change at the data layer and you should be ok either way you go.

    0 讨论(0)
  • 2021-01-23 02:49
    1. Stored procedures. Prevents all sorts of possible issues with injection, maintenance. Put database code where database code belongs.

    2. ORM tool (like Hibernate, Subsonic, etc.) means you never see a line of T-SQL in the first place. Steeper learning curve, but a great practice to start sooner rather than later.

    0 讨论(0)
  • 2021-01-23 02:50

    I avoid harder coded SQL at all costs. I prefer to call Store Procedures.

    If you are using .NET 3.5 and MS SQL Server you might look at LINQ, which then your SQL statements are in code.

    0 讨论(0)
  • 2021-01-23 02:52

    Some ideas:

    1. At the database level, restrict the application user from executing objects other than stored procedures.
    2. Use a database library that either binds SPs to classes, or only works with SPs.
    3. Coding policy combined with Code Reviews/Walkthroughs.

    These may not be the friendliest approaches, but they do have a value in certain environments.

    0 讨论(0)
  • 2021-01-23 02:56

    You really should build applications for a particular data model.

    If your underlying data model changes, which is about the only thing that should require a SQL statement change, there's really no way to avoid doing a code change as well.

    I don't think there's anything wrong with hard-coded SQL Statements, myself. There are some code generators for handling databases, but you still have to design it around a particular known data model, so you still have the same problem if the model changes -- code has to change.

    0 讨论(0)
提交回复
热议问题