Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

.net - Converting between SQL char and C#

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

If using the following code:

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 to parameterValue?

I already have method like this when the parameterValue is of type string, so this could be a problem when telling the difference between SqlDbType.Char and SqlDbType.Varchar

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

char, varchar, nchar, nvarchar are actually strings

the size helps to determine how long the string is...

by the way

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

varchar(2) will be "1"

the n part stands for unicode, so everything inside those fields will be in Unicode.


normally we use nvarchar to save some space on the data, as if you have a char(250) the database will always save the full length, as an empty varchar(250) will be nothing.

In our programming language we then use padding to do what char does, for example, in C#

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

will output " 1" and "1 " respectively.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...