FormatException for inserting date into database - c#

I get the formatException whenever I try to insert a date in the database.
I converted a date into a string and attempted to insert into a database. I have tried all means but it is caught as an exception. Find the code below:
$ DateTime date = Convert.ToDateTime(rows["Limit_maturity_date"].ToString());
string newdate = date.ToShortDateString();//.Replace("/","");
DateTime dd = DateTime.ParseExact(newdate, "M/d/yyyy", CultureInfo.InvariantCulture);
queryString = "INSERT INTO Table (CODE, NUM, CCODE, LCODE, SACCODE, LIM, L_DATE)" +
" VALUES ('" + int.Parse(rows["code"].ToString()) + "','" + int.Parse(rows["number"].ToString()) + "','" + int.Parse(rows["Ccode"].ToString()) + "','" + int.Parse(rows["Lcode"].ToString()) + "','" + int.Parse(rows["Sacode"].ToString()) + "','" + int.Parse(rows["limit"].ToString()) + "','" + newdate "')";

Fundamentally, you're approaching the problem of inserting data into the database incorrectly.
You're converting everything into strings, and including those strings in the SQL. Don't do that. Use parameterized SQL instead, and just put the values directly into the parameters, with no conversions to strings first. This solves three problems:
SQL injection attacks
Mixing code (SQL) and data (parameter values)
Problematic string conversions
It looks like you've got a lot of string conversions going on, and I suspect there's no need for any of them. Any time you're tempted to convert a value to a string, ask yourself whether you really have to. Any time you write code which converts a value to a string and then to another type, like this:
int.Parse(rows["code"].ToString())
... you should be really suspicious. What's the execution-time type of rows["code"]? Could you just use a cast instead?

Related

The selection sql statement is not responding to date value

I am trying to select items from a database where their date equals the date in the Session. It says there is no row at position [0][2], but there is actually a row there. This is my code:
DateTime b = Convert.ToDateTime(Session["Dat"]);
int D = b.Day;
int M = b.Month;
int Y = b.Year;
string dat = M + "/" + D + "/" + Y ;
DataTable m;
m = DAL.SelectFromTable(
"SELECT * FROM [ToDoList] where [UserID]='" + k + "' and [D]="+ dat);
if (m.Rows.Count > 0)
{
Response.Write("</br></br></br><center>" + m.Rows[0][2].ToString() + "</center>");
}
Access requires dates to be surrounded by #.
Assuming DAL is not written by you, and you don't really have the option to correctly and securely query the database, you would have to do something like:
...and [D] = #" + dat + "#"
However, #thisextendsthat has good point that this will probably return no results because you would have to have the time portion of the date exactly as the data is in the database and you are only using month, day and year to build the date.
You could also get around the time portion by selecting a range:
... and [D] BETWEEN #" + dat + "# AND #" + // one day greater than your date at midnight + "#"
But if you do that you have to be careful not to create an impossible date like May 32, for instance.
Be sure to thank your teacher for continuing to train students to code insecurely, keeping SQL injection vulnerabilities right at the top of the OWASP top 10, right where it belongs.
There is no reason to reinvent the wheel, just use method ToString:
DateTime b = Convert.ToDateTime(Session["Dat"]);
DataTable m;
m = DAL.SelectFromTable("select * from [ToDoList] where [UserID] = '" + k + "' and [D] = #" + dat.ToString("yyyy'/'MM'/'dd") + "#");
As Crowcoder says, which DB are you using? That will help determine how you ought to be sending dates into your queries.
If the underlying field is a datetime then you may need to explicitly trim the time part from the value in order to compare to a date. In Sql server:
...where CAST([D] as DATE) = [The date passed in from from C#]
Otherwise you might be comparing today at some arbitrary time to today at midnight, which won't give you what you want.
Also, please think think about paramterising your Sql queries - building up a string literal like this is bad practice and leaves your app vulnerable to Sql injection attacks.

How to store the date in dd/MM/yyyy in sql server?

Here this is my code
DateTime datetime = DateTime.Today;
labelDate.Text = datetime.ToString("'dd'/'MM'/'yyyy");
DateTime d = datetime;
SqlConnection con = new SqlConnection();
con.ConnectionString= #"data source = desktop-u9dun78\sqlexpress;database = Al_Yousuf_Db;integrated security=SSPI";
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO StockEntryTB(Date,Product_No,Product_Name,Quantity,Original_Cost,Selling_Cost)VALUES('" + d + "'," + textBoxProdNo.Text + ",'" + textBoxProdName.Text + "','" + textBoxQuantity.Text + "'," + textBoxOriginalCost.Text + "," + textBoxSellingCost.Text + ")", con);
cmd.ExecuteNonQuery();
con.Close();
But its stored the date in yyyy/dd/MM format. like 2016-06-11(2016/june/11), but I want to store like 11/06/2016.
Stop that!
You have a bad habit to kick as choosing the wrong data type in your SQL Server. You should never store your DateTime values as a string.
In SQL Server, datetime values stored as a binary. You can see some of format that just SQL Server shows you. But under the hood, it doesn't have any implicit format.
That's why, you should insert as a DateTime to your database and get DateTime values from your database. "Format" concept only applies when you textual (string) representation of that DateTime values.
Instead;
Define your Date column as datetime or datetime2 type.
Insert your DateTime value directly with a parameterized query instead of a string.
Also use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
As a last thing, Date might be a reserved keyword in future SQL Server versions, you might wanna use it as [Date] instead. But as a better solution, change your column name to non-reserved word.
You can format your date after retrieving from database.
C#:. String.Format("{0:d/M/yyyy HH:mm:ss}", dt);
Where dt is the Datetime type variable containing your date you want to format.

Error sql:The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I tried to enter the date of the current day with the following code:
string now = (DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year).ToString();
string tm = (DateTime.Today.Hour + ":" + DateTime.Today.Minute).ToString();
string sql2 = string.Format("INSERT INTO Kabala2 (Nu_kabala,Ma_num,Sk,Seif_hacnasa,Seif_name,Date) VALUES('{0}','{1}','{2}','{3}','{4}','{5}')", n, Session["Ma_num"], lprice, lkod,des, now );
Dal.DoQuery(sql2);
when I run this code it shows me the error in the title :
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value
How do I solve it?
------------------edit
i changed it to:string now = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss"); and it works.
now i have another problem, when i run the code below it shows me the error:Error converting data type varchar to numeric.
string now = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss");
string tm = DateTime.Now.ToString("HH:mm:ss");
string sql = string.Format("INSERT INTO Kabala1 (Nu_kabala,Ma_num,Date,Time,Total,Status,Name,User_n) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", n, Session["Ma_num"], now, tm, lprice, "ddffs", Session["user"], "ddffs");
Dal.DoQuery(sql);
string sql2 = string.Format("INSERT INTO Kabala2 (Nu_kabala,Ma_num,Sk,Seif_hacnasa,Seif_name,Date) VALUES('{0}','{1}','{2}','{3}','{4}','{5}')", n, Session["Ma_num"], lprice, lkod, des, now);
Dal.DoQuery(sql2);
string sql3 = string.Format("INSERT INTO Kabala3 ((Nu_kabala,Msd,Ma_num,Kind_pay,Name_pay,Date_pay,Sk,Ms_sek,Snif,Bank,Date_klita,Seif) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", n,"1", Session["Ma_num"],"13", "ddffds", now, lprice, this.card.Text, this.mm.Text, this.yy.Text, now, lkod);
Dal.DoQuery(sql3);
You can Use DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss") //Whatever format...
or Use direct sql instead using CONVERT method. Syntax is
in your case, use the 103 format for the date
CONVERT(VARCHAR,DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year,103)
and 108 for the time
CONVERT(VARCHAR, DateTime.Today.Hour + ":" + DateTime.Today.Minute + ":00" ,108)
whould give format of hh:mm:ss
full reference from the following w3 link:
http://www.w3schools.com/sql/func_convert.asp
The standard form for dates in MySQL is YYYY-MM-DD. I would suggest using this format. Perhaps this will create the string in the right format:
string now = (DateTime.Today.Year + "-" + DateTime.Today.Month + "-" + DateTime.Today.Year).ToString();
Just Change the date settings in your computer or lap. I hope you know how its is done !
If you don't...
choose your calendar from right bottom.
then choose change date and time settings
then choose change date and time
then choose change calendar settings
then in date formats> change short date as either MM/dd/yyyy or dd/MM/yyyy. Choose which is right for your computer. For me it was MM/dd/yyyy.

Conversion of a Varchar Datatype to a datetime resultant in an out of range

I have problem. I can' identify my mistake...
int dt = Convert.ToInt32(Items.Rows[T1]["F14"].ToString().Trim());
int mn = Convert.ToInt32(Items.Rows[T1]["F15"].ToString().Trim());
int yr = Convert.ToInt32(Items.Rows[T1]["F16"].ToString().Trim());
string DtString = mn.ToString().Trim() + "/" + dt.ToString().Trim() + "/" + yr.ToString().Trim();
DateTime RegExp = Convert.ToDateTime(DtString);
exp_date is datetime field in sqlserver.
string MyDtQry = "UPDATE MyTable SET exp_date='" + RegExp + "' where MyTable.id_no='" + AlmIDNo + "'";
But I'am getting the error:
Conversion of a Varchar Datatype to a datetime resultant in an out of range
Well, I would approach the task very differently:
After getting the day, month and year as integers I definitely wouldn't stick them back together and parse them. Just use:
// Note the meaningful variable names here, btw...
DateTime date = new DateTime(year, month, day);
When updating the database, I wouldn't put the value directly into the SQL statement. Use a parameterized SQL statement instead, and set the parameter to date. That way you don't need to worry about the database expecting a different date format to the one you provide. In general, you should always use parameterized SQL rather than embedding the values directly into the SQL - as well as helping with this kind of situation, it avoids SQL injection attacks.
Now, after doing all of that, if you're still getting an error, you should check what actual data you're trying to insert. Maybe the data in Items really is out of range for SQL Server.
It is hard to see exactly since you don't show any of your inputs; however, the following is clearly dangerous:
DateTime RegExp = Convert.ToDateTime(DtString);
string MyDtQry = "UPDATE MyTable SET exp_date='" + RegExp + "' where MyTable.id_no='" + AlmIDNo + "'";
Even if we gloss over the fact that you should be using parameters (you really should), you would need to format this date in the way that SQL server expects - which could be very different to the local format.
However; don't bother formatting it! Use a parameter for this, and it'll go away. This doesn't need to be hard - for example with dapper:
DateTime RegExp = new DateTime(yr, mn, dt);
connection.Execute("UPDATE MyTable SET exp_date=#exp where MyTable.id_no=#id",
new { exp = RegExp, id = AlmIDNo });
and done; fully safe from both injection and the (more likely in this case) issue of formatting data as strings.
This must be problem of the format you are specifying, like instead of month column you might be saving date value column.

How do I insert and query a DateTime object in SQLite DB from C#?

Consider this snippet of code:
string sDate = string.Format("{0:u}", this.Date);
Conn.Open();
Command.CommandText = "INSERT INTO TRADES VALUES(" + "\"" + this.Date + "\"" + "," +this.ATR + "," + "\"" + this.BIAS + "\"" + ")";
Command.ExecuteNonQuery();
Note the "this.Date" part of the command. Now Date is an abject of type DateTime of C# environment, the DB doesnt store it(somewhere in SQLite forum, it was written that ADO.NET wrapper automatically converts DateTime type to ISO1806 format)
But instead of this.Date when I use sDate (shown in the first line) then it stores properly.
My probem actually doesnt end here. Even if I use "sDate", I have to retrieve it through a query. And that is creating the problem
Any query of this format
SELECT * FROM <Table_Name> WHERE DATES = "YYYY-MM-DD"
returns nothing, whereas replacing '=' with '>' or '<' returns right results.
So my point is:
How do I query for Date variables from SQLite Database.
And if there is a problem with the way I stored it (i.e non 1806 compliant), then how do I make it compliant
The ADO.NET wrapper can't convert the DateTime values to ISO 8601 (not 1806) if you convert it to a string and put it in the query. You need to use parameters for that:
Command.CommandText = "INSERT INTO TRADES VALUES (#Date, #Atr, #Bias)";
Command.Parameters.Add("#Date", this.Date);
Command.Parameters.Add("#Atr", this.ATR);
Command.Parameters.Add("#Bias", this.BIAS);
Conn.Open();
Command.ExecuteNonQuery();
(Besides, you converted the DateTime value to a string and put in the sDate variable, but then you used the DateTime value to produce the SQL query anyway.)
The same applies when getting the data:
Command.CommandText = "SELECT * FROM <Table_Name> WHERE DATES = #Date";
Command.Parameters.Add("#Date", theDate);
About your second problem, if SQLite is anything close to SQL Server,
SELECT * From where Dates = "YYYY-MM-DD' will not return because it will probably implicitily convert YYYY-MM-DD to YYYY-MM-DD 00:00:00. You might need to add a range (e.g. greater or equal than today and smaller than tomrrow).
#Guffa, I am getting "Cannot Convert from System.DateTime to System.Data.DbType" on this line:
Command.Parameters.Add("#Date", this.Date);

Categories

Resources