Why new MySqlParameter (& quot; @ val & quot;, 0). Value =

Source: Internet
Author: User

Some time ago, when my colleagues wrote code, they found that MySQL Data Tables were often inserted with magical null values. After tracking the code for half a day, they finally found the problem:

 
 
  1. DbParameter p = new MySqlParameter ("@ val", 0 );
  2. Debug. Assert (p. Value = 0); // Assert fails. p. Value is actually null.

After analysis for half a day, no reason was found. I guess MySql. Data treats 0 as null. I thought, it shouldn't be. There's no reason at all. What a normal value 0 is in the database! So I downloaded the source code of MySql. Data for debugging and tracking ...... Then I found a terrible thing.

MySqlParameter has several BUILD functions, two of which are stated in this statement.

 
 
  1. Public MySqlParameter (string name, object value ){
  2. //......
  3. }
  4.  
  5. Public MySqlParameter (string name, MySqlDbType ){
  6. //......
  7. // MySqlDbType is an enumeration type.
  8. }

P = new MySqlParameter ("@ val", 0) actually calls the second build function. 0 is converted to MySqlDbType. decimal is passed in, and no Value is assigned for its Value. Of course, p. the Value is null.

Then, will not all input integers be treated as enumeration ...... Otherwise, if the input value is not 0, the call is the first build function, and 1 is processed as an object!

Then I am wondering why 0 will be automatically converted to the enumeration type for processing, rather than 0 will be treated as an object? Why? Who can tell me the answer?

The problem is solved ......

 
 
  1. DbParameter p = new MySqlParameter ("@ val", (object) 0 );
  2. Debug. Assert (p. Value = 0); // Assert successful

 

This article from the "Edge City inn xuehai Wuxi" blog, please be sure to keep this source http://jamesfancy.blog.51cto.com/2516291/1162445

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.