Skip to content

Commit 0c962c3

Browse files
committed
Add "AddWithValue" documentation.
1 parent 1662ac0 commit 0c962c3

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
date: 2020-01-06
3+
menu:
4+
main:
5+
parent: getting started
6+
title: Using AddWithValue
7+
weight: 70
8+
---
9+
10+
# Start Using AddWithValue
11+
12+
There's [some advice](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) out there
13+
that insists calling `cmd.Parameters.AddWithValue` "needs to stop".
14+
15+
That advice may be valid for Microsoft SQL Server, but is inapplicable to MySQL Server. If you use MySQL, **you should freely use
16+
`cmd.Parameters.AddWithValue("@paramName", value);`**.
17+
18+
The primary reason that `AddWithValue` is OK to use is that MySQL's [text protocol](https://dev.mysql.com/doc/internals/en/text-protocol.html)
19+
is not typed in a way that matters for client-side type inference.
20+
21+
All numbers are sent as ASCII digits (e.g., `1234`), whether they're typed as `DbType.Int32` or `MySqlDbType.NewDecimal`, or left untyped
22+
and the value is just assigned a `long` or `float` or `decimal`. (Of course, if you're trying to store a floating point number in an integer column,
23+
the server will have to convert/coerce it, but that isn't affected by the parameter type set in your C# code.)
24+
25+
Similarly, all strings are sent as UTF8-encoded bytes (e.g., `'abcd'`) regardless of the charset of the column they're being inserted into
26+
(the server will perform a conversion if necessary).
27+
28+
It doesn't really matter what you set the `MySqlParameter.DbType` or `MySqlParameter.MySqlDbType` property values to, so don't worry about
29+
it; just call `AddWithValue`, let MySqlConnector serialize the type on the wire based on its .NET type, and let MySQL Server perform
30+
any conversion that might be necessary.

0 commit comments

Comments
 (0)