mayowa ogundele
mayowa ogundele

Reputation: 463

FormatException for inserting date into database

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 "')";

Upvotes: 2

Views: 221

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500555

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:

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?

Upvotes: 4

Related Questions