I am trying to insert an entry into a database:
mySqlCommand.CommandText = "INSERT INTO table_name (col1, col2) values (#number, #word);";
mySqlCommand.Parameters.Add("#number", MySqlDbType.Int32);
mySqlCommand.Parameters.Add("#word", MySqlDbType.VarChar);
mySqlCommand.Parameters["#number"].Value = 0110;
mySqlCommand.Parameters["#word"].Value = "Hello";
However when I get it back out, it's stored as 110 instead of 0110. How can I get it to recognise the leading 0?
Well your datatype is integer. when 0110 is cast to integer it becomes 110.
To achieve your goal you need to set its datatype as varchar both in table and
MySqlDbType.Int32 to MySqlDbType.VarChar.
Hope this will help you.
There is nothing like leading 0 in int. however if u want to store the leading 0 then you can convert data type of that field to Varchar..
or by programmatically you can also pad 0 in any variable but again it will be converted to string.
Like this
int Anynumber= 5;
string AnynumberWithZero = string.Format("{0}", Anynumber.ToString().PadLeft(2, '0'));
Result will be"05"
Related
Imagine this code:
string value = "1.23";
string query = "UPDATE MYTABLE SET COL1=#p1";
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("#p1", value);
cmd.ExecuteNonQuery();
On my database it will work with value="1.23" if COL1 is decimal type column. But it will fail if value is "1,23" (comma instead of a dot as a decimal point). The error is
Error converting data type nvarchar to numeric
I'd like it to work in both cases with "value" being a string variable.
Unfortunately I cannot just replace comma for the dot as this code is going to be more universal, dealing both with numeric and varchar columns
Is there any way that an query accepts a parameter with number written as a string both with dot and a comma and correctly puts it in into table?
Thanks for any help
If the value isn't semantically a string, you shouldn't send it as a string. The type of the parameter value is important, and influences how it is transmitted and can lead to culture issues (comma vs dot, etc).
If the value is semantically a decimal, then use something like:
string value = "1.23";
var typedValue = decimal.Parse(value); // possible specifying a culture-info
//...
cmd.Parameters.AddWithValue("#p1", typedValue);
Then it should work reliably.
Unrelated, but you can make ADO.NET a lot easier with tools like "Dapper":
connection.Execute("UPDATE MYTABLE SET COL1=#typedValue", new { typedValue });
I'm having a problem when I insert a value it will show a error:
incorrect integer value: "for column 'taxi_id' at row 1
string
insertcmd = "INSERT INTO taxi(taxi_id) VALUES ('#taxi_id')";
myCmd.Parameters.AddWithValue("#taxi_id", BigInteger.Parse(merchantId,NumberStyles.Integer));
taxi_id in database is of type Bigint(255).
Can anyone help?
Since you are using quotes around #taxi_id, it is considered a literal textual value and not a parameter.
Remove the quotes so #taxi_id becomes a parameter:
INSERT INTO taxi(taxi_id) VALUES (#taxi_id)
I have 100 textboxes in 00 to 99 manners in form. I want to store first 0 to 9 in double digit format like 00, 01, 02, .... 09. How can i store it in sql database in that format without making it a string. I am doing project in c#.
If you need to have those values in that format just in your table;
You need to run a query to insert a new row or update a valid row;
string query = string.format("Insert Into <table name> Values (list of values)", int value(s));
or
string query = string.format("UPDATE <table name> Set (list of '<field name> = <value>'s)", int value(s));
You need just use {0:00} instead of {0} in your query string.
If you use sqlCommand at setting parameters use it in this way = string("{0:00}", int value)
Note: all codes are sample, you need to generate your own codes.
If you need to store your value with format you should use one of char data-types in your table.
If your filed is "int", I think it will be not possible. As 09 is 9 in integer. As per thumb rule of integer the leading ZERO have no value.
But you can always SELECT with formatting OR else use "varchar" type to store it as you need.
Hope I am clear enough..!!
I have a very BIG PROBLEM.
I want to delete a row from my database sql in C#.
here is my code:
int x = Convert.ToInt32(dataGridView1.SelectedCells[0].Value);
cmd.Parameters.Clear();
cmd.CommandText = "delete from Table2 where Name=#N";
cmd.Parameters.AddWithValue("#N", x);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
and finally im get a problem
Input string was not in a correct format.
Help me.
I get the error in first Line.
First problem:
dataGridView1.SelectedCells[0].Value is not a valid integer value, so Convert.ToInt32 fails.
Did you mean
string x = dataGridView1.SelectedCells[0].Value;
instead?
Second problem:
You are comparing the Name field to an integer value. I'm assuming Name is a _string_ value in the database (otherwise it's poorly named). When SQL looks for matching values, it will try to convert every value ofNamein the database to a number. if ANY value in theName` field is not a valid number, the query will fail.
I've read that null or empty string will return 0 (to be confirmed)
Here my guess :
Depending of your country, numbers should be wrote :
1.234
or
1,234
Solution
Hugly solution : You can simply do a :
Convert.ToInt32(dataGridView1.SelectedCells[0].Value.Replace(".",","));
Good solution : Or use Convert.ToInt32(String, IFormatProvider) :
Convert.ToInt32(dataGridView1.SelectedCells[0].Value,CultureInfo.CurrentCulture)
EDIT -1 without comment, i'm please to help.
scenario:
I have a database having a record 001234 and I am calling it with cmd.executescaler(); into a int variable. The problem is when I retrieve the saved data (001234) data from that variable it gives only 1234. 00 in 001234 are important, this was the problem first coming in db where sql omits the first zero's then I changed the datatype to nvarchar which works, how I can retrieve the data on the form exactly 001234.
Note: I cannot take the data into string as I have to also apply some calculations on them.
using Sql Server visual studio 2010 c#
Hope it is clear not vague. If you need more information tell me.
Thanks in advance.
Numeric datatype don't have and can't have leading zeros. So the only way to have leading zeros is to store the value as a string.
However, this is just a matter of formatting the output that is shown to the user. You can read the database value into an int variable, do your calculations and when showing the value, you can do:
string displayValue = String.Format("{0:D6}", intValue);
and show the value of displayValue.
If you want to work on the Code side:
string displayValue = String.Format("{0:D6}", intValue);
If you want to work on the DB side you need a Pad function that allows to write this kind of query:
SELECT dbo.PadString ('8', '0', 5)
->Result: 00008
SELECT dbo.PadString ('abc', '*', 12)
->Result: *********abc
SELECT dbo.PadString ('abc', '0', 7)
->Result: 0000abc
Create a function in T-SQL
CREATE FUNCTION [dbo].[PadString]
(#Seq varchar(16),
#PadWith char(1),
#PadLength int
)
RETURNS varchar(16) AS
BEGIN
declare #curSeq varchar(16)
SELECT #curSeq = ISNULL(REPLICATE(#PadWith, #PadLength - len(ISNULL(#Seq ,0))), '') + #Seq
RETURN #curSeq
END
If those leading zeros have some meaning and can't be left out, conversion can be done:
int number = 0;
string strNumber = (string)cmd.ExecuteScalar();
if(int.TryParse(strNumber, out number))
{
// process number
// if you want some output to be formatted with leading
// zeros you can use PadLeft method
int totalNumberOfDigits = 6;
string strResult = number.ToString().PadLeft(totalNumberOfDigits, '0');
}
you can use string.PadLeft() in c# after retrieving your number, as you have fixed length numbers
example from msdn,
string str = "forty-two";
char pad = '.';
Console.WriteLine(str.PadLeft(15, pad)); // Displays "......forty-two".
Console.WriteLine(str.PadLeft(2, pad)); // Displays "forty-two".
The reason SQL does this is because 001234 = 1234 in any number format no matter what type it is. As a "Dirty" solution you could cast it as an int which will give you 1234, perform your calculations and then cast your answer back to string adding the leading zeros.
int myValue = Int32.Parse("001234");
int myAnswer = myValue * 2;
string myAnswerString = "00" + myAnswer.ToString();
The best way to go though would be to format your string as suggested by #Thorsten Dittmar. If possible, do not store numeric values in the database as varchar to begin with, however I know that this is sometimes a requirement, but the I cannot see the point on doing calculations on those values.