简体   繁体   中英

Conversion failed when converting date and/or time from character string #2

Here's my code:

DateTime Dob = Convert.ToDateTime("1/1/1800");
DateTime Dod = Convert.ToDateTime("1/1/1800");

if (!string.IsNullOrEmpty(p.birthday))
     Dob = Convert.ToDateTime(p.birthday);

if (!string.IsNullOrEmpty(p.deathday))
     Dod = Convert.ToDateTime(p.deathday);

string query = string.Format("insert into actor values (@name, @biography, @placeOfBirth, @profilePath, @dob, @dod)");
SqlCommand command = new SqlCommand(query, connection);

command.Parameters.Add(new SqlParameter("@name", !string.IsNullOrEmpty(p.name) ? p.name : "not available"));
command.Parameters.Add(new SqlParameter("@biography", !string.IsNullOrEmpty(p.biography) ? p.biography : "not available"));
command.Parameters.Add(new SqlParameter("@placeOfBirth", !string.IsNullOrEmpty(p.place_of_birth) ? p.place_of_birth : "not available"));
command.Parameters.Add(new SqlParameter("@profilePath", !string.IsNullOrEmpty(p.profile_path) ? p.profile_path : "not available"));
command.Parameters.Add(new SqlParameter("@dob", Dob));
command.Parameters.Add(new SqlParameter("@dod", Dod));

connection.Open();
command.ExecuteNonQuery();

The error I get is:

Conversion failed when converting date and/or time from character string

The values for Dod and Dob are below:

在此处输入图片说明

在此处输入图片说明

QUESTION : Is there something wrong with my DateTime objects that SQL doesn't like? If not, what's going on????

You're relying on the ordinal position of your columns... and it could be that those differ from the order of the corresponding values. You might try explicitly naming your target columns. I'm guessing at the column names here.

insert into actor 

values 
(@name, @biography, @placeOfBirth, @profilePath, @dob, @dod)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM