Converting between SQL char and C# - 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

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.

string will work fine if it is 2 characters or shorter

try using AddWithValue method and parce it as string,
it is only a one line. no need to have a seperate method.
command.Parameters.AddWithValue(parameterName, parameterValue);

Related

How to get string back in c# after converting to binary in SQL Server

I have string value key:
TxtProductKey.Text has value "key"
Encode this value
byte[] Key = Encoding.ASCII.GetBytes(TxtProductKey.Text.Trim());
Save it in database table in a column of datatype binary(50) null.
The value in the table looks like this:
0x6B00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Now I am trying to get it back in string value that I entered is Key
byte [] TempKey = (byte[])LicenseInfo.Tables[0].Rows[0]["ProductKey"];
var newText = Encoding.ASCII.GetString(TempKey);
but the result I am getting in newText is:
k\0\0\0\0\0\00\
Where am I doing something wrong? I hope for your suggestions
C# code for saving value in database:
Sqlconnection.Open();
SqlCommand Cmd = new SqlCommand("SpAddAttempts", Sqlconnection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#Attempts", SqlDbType.Int).Value = Attempt;
Cmd.Parameters.Add("#Activate", SqlDbType.Bit).Value = Activate;
Cmd.Parameters.Add("#Key", SqlDbType.Binary).Value = Key;
Cmd.ExecuteNonQuery();
CloseConnection();
Stored procedure is:
ALTER PROCEDURE [dbo].[SpAddAttempts]
#Attempts INT,
#Activate BIT,
#Key BINARY
AS
BEGIN
UPDATE License
SET Attempts = #Attempts,
Activate = #Activate,
ProductKey = #Key
WHERE LicenseId = '1'
END
I don't think you can: you only stored a single byte (the equivalent of char k) in your db table.. 0x68 is k, the next byte is 0x00 - ascii null - string terminator - whatever your language of choice will refer to it as, it's definitely not e
So, because only the first byte has been preserved and the rest is ascii NUL 000000000000000000000000....), there's no way to know whether the rest of the value was ey, eyboard, oolaid etc.. The fault is during the storing of the value in the table (you didn't show code for that part) - it's only stored the first byte
I recommend you store this text as text, not binary; it seems like an unnecessary world of pain to store it as binary when it starts life as text and you clearly want it back out as text.
EDIT: Now you've posted the code that does the saving, I can see youve declared the parameter as type Binary, but you havent specified a length, so the length is defaulting to 1 byte. This is why only one of your bytes is getting saved. You need to declare the parameter more like this:
cmd.Parameters.Add("#Key", SqlDbType.Binary, binaryData.Length); //dont pass an array longer than what the table can store, or you'll get a "data would be truncated" error

Invalid Argument error for a function

Function
MouldingDetail_UpdateDetails(string mouldItem, string mouldQty, int core, int freerider, decimal plate, string plant, string systemMode)
after passing
MouldingDetail_UpdateDetails( "AX5M211531", '1', 1, 1, '0.5', "CMLD1", string.Empty) when I pass the following as values it shows "invalid arguments"
This is the method's signature:
MouldingDetail_UpdateDetails(
string,
string,
int,
int,
decimal,
string,
string
)
Yet, you're passing:
MouldingDetail_UpdateDetails(
"AX5M211531" (string), // Good
'1' (char), // Wrong! This is supposed to be a string! use "1" instead
1 (int), // Good
1 (int), // Good
'0.5' (invalid char), // Wrong! This shouldn't even compile. Use 0.5M without the single quotes
"CMLD1" (string), // Good
string.Empty (string) // Good
);
'1' isn't a valid string, it's a char instead.
For a proper understanding please read - https://msdn.microsoft.com/en-us/library/cs7y5x0x(v=vs.90).aspx

"Error converting" numeric input to correct TSQL type (possible Bug)

As of now I am encountering this kind of bug
Error converting data type float to decimal.
or
Error converting data type Numeric to decimal
This is my code
using (SqlConnection reportsConn = new SqlConnection(sqlConnWriter))
{
reportsConn.Open();
SqlCommand AddReconItem = new SqlCommand();
AddReconItem.Connection = reportsConn;
AddReconItem.CommandType = CommandType.StoredProcedure;
AddReconItem.CommandText = "Updater.usp_AddReconcileItems";
// AddReconItem.Parameters.Add("#varible",SqlDbType.Decimal
AddReconItem.Parameters.AddWithValue("#ITEMWEIGHT", Math.Round(Convert.ToDouble(WeightTextBox.Text+".00"), 2));
AddReconItem.Parameters.AddWithValue("#ITEMPRINCIPALAMT", Math.Round(Convert.ToDouble(PrincipalTexAmTextBox.Text + ".00"), 2));
AddReconItem.Parameters.AddWithValue("#FORLOANMONTH", Convert.ToDateTime(YearDropDownList.SelectedValue + "/" + MonthDropDownList.SelectedValue));
AddReconItem.Parameters.AddWithValue("#STORAGEGROUPID", StorageNameDropDownList.SelectedValue);
AddReconItem.Parameters.AddWithValue("#BRANCHCODE",BranchCodeTextBox.Text);
AddReconItem.Parameters.AddWithValue("RECONID", ReconTypeDropDownList.SelectedValue);
AddReconItem.Parameters.AddWithValue("#PAWNTIX",PwnTicketTextBox.Text);
AddReconItem.Parameters.AddWithValue("#CREATEDBY", Session["UserID"].ToString());
AddReconItem.ExecuteNonQuery();
}
When I input, 123 for principalamt and itemweight it accepts the answer and treats it as a decimal, but when I input 1234 for itemweight and still 123 for Principalamt it shows that error, if I remove the conversion and change it to Convert.ToDecimal it shows Error converting data type Numeric to decimal if I use it as text it shows Error converting data type varchar to decimal
Is this a bug or something? I can't seem to find a way I tried many options but none of them have been working
My database columns are below:
I really hope you can help me understand this phenomenon
EDIT
This is the first time I saw a program accepting 123 as a valid input while 1234 is not, my database Decimal (38,6) is very large enough to accommodate this input that's why I'm looking for the answer or known bugs that can solve this problem, thank you.
I'd suggest using Decimal.TryParse instead of Convert for your principalamt value and then maybe debugging and inspecting how the value gets converted to a valid Decimal for your Money column. For example something like;
bool valid;
var dbl = Convert.ToDouble("1234.00");
valid = Double.TryParse("1234.00", out dbl);
var dcml = Convert.ToDecimal("1234.00");
valid = Decimal.TryParse("1234.00", out dcml);
I'm not sure if you should be using Double as a data type when trying to store the resultant value in a Decimal field. Double represents floating type numbers and I think you should be using the Decimal data type for your Money column as mentioned in this answer.
For ItemWeight, with a data type of decimal(38,6), you'll end up with 6 decimal places regardless of your rounding I think. Try the following in SQL Server and make sure the parameter type for #ITEMPRINCIPALAMT is DECIMAL as well (similar to my example below).
DECLARE #Var decimal(38,6) = 1234.00
DECLARE #Tbl AS TABLE
(
Test decimal(38,6)
)
INSERT INTO #Tbl (Test) Values (#Var)
SELECT * FROM #Tbl

convert a double with a comma to a variable with a point to use in sql statement

I use my double in a select statement:
code:
SqlCommand command = new SqlCommand("SELECT min(Score) FROM "+ table +" WHERE [" + sportEvent + "] < (#result);", connect);
command.Parameters.AddWithValue("#result", result);
everything works fine if double result is an integer but not if result is a comma number (example 11,34) --> it should be 11.34 to work (point instead of comma)
How can I change a double 11,34 into 11.34 ?
It appears that your code sets a string parameter as a constraint for a DB value of numeric type, letting the database do the conversion. This is not a good idea, because it takes control away from your program: should DBA decide to reconfigure your backend database to "understand" commas instead of dots, your program will stop working!
Currently, your double is in a locale-specific format. You need to parse it using the locale-specific format provider, and then set the value that you get back from the parser as the parameter of your SQL query. Assuming that the current culture is one that is using commas as decimal separator, you can do this:
command.Parameters.AddWithValue(
"#result"
, double.Parse(s, CultureInfo.CurrentCulture)
);
You can use this
result.ToString(CultureInfo.InvariantCulture)
You could try changing the variable into string:
result.ToString().Replace(',','.');
This will replace the comma with a dot.
If result is Double then:
command.Parameters.Add("#result", SqlDbType.Float).Value = result

Specified cast is not valid exception in ms access query using C#

hey guys m having this wierd exception of cast though my datatypes are correct in db:
string sql =
string.Format(
#"select aim_network_id,aim_network_name,oxinetwork_id,pack_id,pack_name,p_face_value,pm_prefix from Operator where aim_network_id='{0}'",
gridbackOffice["aim_network_id", gridbackOffice.CurrentCell.RowIndex].Value);
OleDbCommand getSelectedGridDatecmd = new OleDbCommand(sql, conn);
OleDbDataReader reader = getSelectedGridDatecmd.ExecuteReader();
while (reader.Read())
{
txtAimNetworkID.Text = reader.GetString(0);
txtAimNetworkName.Text = reader.GetString(1);
txtPARNetworkID.Text = reader.GetString(2);
txtPARFaceValue.Text = reader["p_face_value"].ToString();
//in above line if i'm doing this `reader.GetString(5)` then i'm getting specified cast exception and that to randomly i.e some time it works fine and suddenly sometime gives this exception
txtPARPackID.Text = reader.GetString(3);
txtPARPackName.Text = reader.GetString(4);
txtPARPMPrefix.Text = reader["pm_prefix"].ToString();
}
I'm little bit confused if m using this reader["p_face_value"].ToString() then my code is running very smoothly but whats the issue with using this reader.GetString(5) , according to me both method return string, nebody had faced this error b4 ?
....Error is at 4th and 7th line in while loop.
Exception:Specified cast is not valid (InvalidCastException unhandled)
According to MSDN, OleDbDataReader.GetString() does not perform any conversions before attempting to cast to a string - therefore the data retrieved must already be a string.
If there is a chance that the value in that column could be null, the docs suggest that you should check if the value is null first:
if ( !reader.IsDBNull(5) ) {
txtPARFaceValue.Text = reader.GetString(5);
}
Calling reader["p_face_value"] on a null value returns DBNull - and when you call ToString() on DBNull, you get an empty string.
From MSDN:
No conversions are performed;
therefore the data retrieved must
already be a string.
If the column is not a string type, you'll need to use the .ToString() method to convert it.
What is the datatype of p_face_value in your database?
Based on the error description given it seems that this is not a string type, so when you call:
reader.GetString(5)
the code errors out as it cannot convert whatever type it is to a string. The .ToString() method will work as this does not use a cast.
You should use GetString only when the column is a string-equivalent type in the database (like varchar), in your case "p_face_value" seems to be a numeric type, therefore it cannot simply convert it to a string.
The way you're doing it right now is the right way.

Categories

Resources