Convert between SQL char and C #

If I want to insert in a database column of type char (2) from C #. What type of data would I use in C #?

If the following code is used:

private static SqlParameter addParameterValue(string parameterName, ? parameterValue, SqlCommand command) { SqlParameter parameter = new SqlParameter(parameterName, SqlDbType.Char); parameter.Value = parameterValue; command.Parameters.Add(parameter); return parameter; } 

What type would I give the value parameter?

I already have such a method when the Value parameter has a type string, so this can be a problem when calculating the differences between SqlDbType.Char and SqlDbType.Varchar

+6
source share
3 answers

string will work fine if it is 2 characters or shorter

+4
source

char , varchar , nchar , nvarchar are actually strings

size helps determine how long the string ...

by the way

char has a fixed length, so if you want to have "1" in char(2) , the content will be actual "1 "

varchar(2) will be "1"

part of n stands for unicode, so everything inside these fields will be in Unicode.


usually we use nvarchar to save some space in the data, as if you have char(250) , the database will always keep the full length, since empty varchar(250) will not be anything.

In our programming language, we use add-ons to do what char does, for example, in C #

 "1".PadLeft(2); "1".PadRight(2); 

outputs " 1" and "1 " respectively.

+6
source

try using the AddWithValue method and parse it as a string,

this is only one line. no need to have a separate method.

 command.Parameters.AddWithValue(parameterName, parameterValue); 
+1
source

Source: https://habr.com/ru/post/900599/


All Articles