The trap of SQL statements with parameters in ADO. NET, ado. netsql

Source: Internet
Author: User

The trap of SQL statements with parameters in ADO. NET, ado. netsql
1. Use Parameter

// Using the constructor method, it is not recommended to write Parameter p = new Parameter ("@ id", value); cmd. parameters. add (p); // It is recommended to write Parameter p = new Parameter () {ParameterName = "@ id", Value = "Value"} in this way by using the object initiator "}; cmd. parameters. add (p );

// What are the purposes of recommendation and not recommendation? As described below:

2. Use the Parameter Array
// It is not recommended to write Parameter [] pms = new Parameter []; {new Parameter ("@ id", value );......}; cmd. parameter. addRange (pms); // recommended SqlParameter [] pms = {new SqlParameter ("@ id", SqlDbType. varChar, 50 ),.......}; parameters [0]. value = "Value"; cmd. parameter. addRange (pms );

// What is the reason for recommendation and not recommendation? As described below:

3. Parameter ("@ id", value) trap

We do not recommend the use of Parameter ("@ id", value) as described in steps 1 and 2 above. Why?

The reason is that this is the case once.

New SqlParameter ("@ aa", 0); the constructor in the Red Circle is called strangely.

The result is that the item originally assigned a value in the database is changed to null.

Why is 0 treated as the MySqlDbType by the compiler?

The reason is that MySqlDbType is an enumeration. 0 exactly corresponds to the Decimal type.

 

So to avoid this situation,

We recommend that you use the object initializer,

Alternatively, you can directly use the constructor with DbType to instantiate it and then assign a value.

In short, the direct use of constructor methods is a bit pitfall ~
 

 

Related Article

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.