简体   繁体   中英

Is it good practice to execute a stored procedure by writing it as a string?

Is this following a good practice or not?

cmd.CommandText = "StoredProcedureName_InsertUserDetails"; //Is this line a good or bad since Sql injection is possible here.
cmd.Parameters.Add(new SqlParameter("@name",SqlDbType.VarChar)).Value=name;
cmd.Parameters.Add(new SqlParameter("@age",SqlDbType.Int)).Value=age;

Here is your code with added Commandtype :

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoredProcedureName_InsertUserDetails"; // This line is ok
cmd.Parameters.Add(new SqlParameter("@name",SqlDbType.VarChar)).Value=name;
cmd.Parameters.Add(new SqlParameter("@age",SqlDbType.Int)).Value=age;

Is it good practice to execute a stored procedure by writing it as a string?

What could go wrong?

  • SQL Injection? When you set CommandText as hard-coded string as shown above, there is no possibility to SQL Injection attack.
  • Stored procedure name not sync with calling code: You can get run-time exceptions if calling code refers to unknown stored proc.
    • Keep your stored procedure creation scripts under version control, near to your code which uses it. This way it is possible to keep stored procedure in sync with C# code.
    • Automatic tests can be created to notice if Stored Proc has breaking changes

If your Stored procedure inserts only single UserDetails entity, you can also make use of Entity Framework. This article shows how to map entity CUD ( Create, Update, Delete ) operations to Stored Procedures automatically by calling MapToStoredProcedures() in Fluent API. Article also explains how you can map your own custom Stored Procedures to your EF Entities.

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