How to use "?" Replace parameters to simplify database operations

Source: Internet
Author: User

I have briefly introduced how to emulate Java in SQL? The implementation scheme that replaces the parameter location, in programming and development, we will implement some strange simple and complex ideas with our own programming concepts, every step from rough to beautiful can make us proud. Although it may be a silly or even brainless idea in the eyes of others, as a programmer, I always think: "programming is not only a technology, but also an art. Even the most boring coding, we also need to complete it with a passionate coding behavior. ", Every attempt and practice can benefit us a lot. Although not every attempt is so correct, at least you can find that this road is impossible, and this is experience.

A little off the question. Let's continue with what we want to talk about.

The SQL we originally needed to write may be in the following format:

 
 
  1. Public UserInfo GetUserInfoById (Guid id ){
  2. String SQL = "SELECT name, age, address, desc FROM UserInfo WHERE id = @ id ";
  3. Sqlparameter param = new SqlParameter ("@ id", id );
  4. // The code for processing UserInfo is omitted
  5. }

However? The new code format is changed:

 
 
  1. Public UserInfo GetUserInfoById (Guid id ){
  2. String SQL = "SELECT name, age, address, desc FROM UserInfo WHERE id =? ";
  3. UnknowSqlParameter castUnknow = new UnknowSqlParameter ();
  4. Sqlparameter [] parameters = castUnknow. CastUnknowMark (ref SQL, id );
  5. // The code for processing UserInfo is omitted
  6. }

It seems that the second type is not much simpler or even a little more troublesome than the first one, but if we add the extension method, it will become easier. For example, the original SQL connection class is as follows:

 
 
  1. Public static class SQLHelper
  2. {
  3. # Region Connection
  4.  
  5. /// <Summary>
  6. /// Database connection
  7. /// </Summary>
  8. Private static SqlConnection connection;
  9.  
  10. /// <Summary>
  11. /// Open the database connection
  12. /// </Summary>
  13. /// <Param name = "connectionString"> connection string </param>
  14. Private static void OpenConnection (string connectionString)
  15. {
  16. Connection = new SqlConnection (connectionString );
  17. Connection. Open ();
  18. }
  19.  
  20. /// <Summary>
  21. /// Obtain the database connection
  22. /// </Summary>
  23. /// <Returns> </returns>
  24. Public static SqlConnection GetConnection ()
  25. {
  26. String connectionstring = ConfigurationManager. ConnectionStrings ["SQL"]. ConnectionString;
  27. If (connection = null | connection. State = ConnectionState. Closed)
  28. {
  29. OpenConnection (connectionstring );
  30. }
  31. Else if (connection. State = ConnectionState. Broken)
  32. {
  33. Connection. Close ();
  34. OpenConnection (connectionstring );
  35. }
  36. Return connection;
  37. }
  38.  
  39. # Endregion
  40.  
  41. # Region Commond
  42.  
  43. /// <Summary>
  44. /// Set SqlCommond
  45. /// </Summary>
  46. /// <Param name = "com"> sqlCommond </param>
  47. /// <Param name = "type"> CommondType </param>
  48. /// <Param name = "values"> parameter </param>
  49. Private static void SetSqlCommond (SqlCommand cmd, string SQL, CommandType comment type, SqlParameter [] values)
  50. {
  51. Cmd. Parameters. Clear ();
  52. Cmd. CommandText = SQL;
  53. Cmd. CommandType = primitive type;
  54. If (values! = Null) cmd. Parameters. AddRange (values );
  55. }
  56.  
  57. # Endregion
  58.  
  59. # Region ExecuteReader
  60.  
  61. /// <Summary>
  62. /// Obtain SqlDataReader
  63. /// </Summary>
  64. /// <Param name = "SQL"> SQL statement </param>
  65. /// <Param name = "values"> parameter value array </param>
  66. /// <Returns> </returns>
  67. Public static SqlDataReader ExecuteReader (this SqlConnection conn, string SQL, params object [] values)
  68. {
  69. Return ExecuteReader (conn, SQL, CommandType. Text, values );
  70. }
  71.  
  72. /// <Summary>
  73. /// Obtain SqlDataReader
  74. /// </Summary>
  75. /// <Param name = "cmd"> SqlCommand </param>
  76. /// <Param name = "SQL"> SQL statement </param>
  77. /// <Param name = "values"> parameter value array </param>
  78. /// <Returns> </returns>
  79. Public static SqlDataReader ExecuteReader (this SqlConnection conn, string SQL, CommandType primitive type, params object [] values)
  80. {
  81. Using (SqlCommand com = new SqlCommand (SQL, conn ))
  82. {
  83. UnknowSqlParameter castUnknow = new UnknowSqlParameter ();
  84. SqlParameter [] parameters = castUnknow. CastUnknowMark (ref SQL, values );
  85. SetSqlCommond (com, SQL, parameter type, parameters );
  86. Return cmd. ExecuteReader ();
  87. }
  88. }
  89.  
  90. # Endregion
  91. }

For convenience and code won't be too long, only the ExecuteReader method is available. Therefore, when we use the previous example, the code will be changed:

 
 
  1. Public UserInfo GetUserInfoById (Guid id ){
  2. String SQL = "SELECT name, age, address, desc FROM UserInfo WHERE id =? ";
  3. SQLHelper. GetConnection (). ExecuteReader (SQL, id );
  4. // The code for processing UserInfo is omitted
  5. }

The current code is very similar to the first code, and the gap is not too far, but it is different when the number of parameters increases. The Code is as follows:

 
 
  1. Public IList <UserInfo> GetUserInfoByNames (param string names)
  2. {
  3. String SQL = "SELECT name, age, address, desc FROM UserInfo WHERE name IN (?) ";
  4. SQLHelper. GetConnection (). ExecuteReader (SQL, id );
  5. // The code for processing UserInfo is omitted
  6.  
  7.  
  8. // Call methods such:
  9. GetUserInfoByNames ("Zhang xiaosan", "Li xiaosi", "Wang xiaowu ")

I believe that you have made a comparison between these methods, and the final method is still the best in any aspect.

The above code is purely explained, right? Other factors need to be considered for the implementation of the alternative parameter idea to be applied in real projects? The practice of substitution parameters is over. Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.