开发者

insert date into SQL

I'm trying to insert a date into a SQL table, but it when the program runs it gives the following error.

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

string dateReleased = DateRel开发者_如何学编程easedDate.Value.ToString("YYYY-MM-DD");

string myQuery = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, dateAdded, developerID, publisherID, consoleID) VALUES('" 
                + GameNameTxt.Text + "', '" + GenreCombo.SelectedValue + "', '" + PlayersNUD.Value + "', '" + OnlineCombo.SelectedText + "', '"
                + dateReleased  + "', 'GETDATE()', '" + DeveloperCombo.SelectedValue + "', '" 
                + PublisherCombo.SelectedValue + "','" + ConsoleCombo.SelectedValue + "')";


Please use parametrized queries. My eyes hurt when I see string concatenations used to construct SQL queries:

using (var conn = new SqlConnection("SOME CONNECTION STRING"))
using (var cmd = new SqlCommand(conn))
{
    conn.Open();
    cmd.CommandText = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, developerID, publisherID, consoleID) VALUES (@gameName, @genreID, @players, @online, @dateReleased, @developerID, @publisherID, @consoleID)";
    cmd.Parameters.AddWithValue("@gameName", GameNameTxt.Text);
    cmd.Parameters.AddWithValue("@genreID", GenreCombo.SelectedValue);
    cmd.Parameters.AddWithValue("@players", PlayersNUD.Value);
    cmd.Parameters.AddWithValue("@online", OnlineCombo.SelectedText);
    cmd.Parameters.AddWithValue("@dateReleased", DateReleasedDate.Value);
    cmd.Parameters.AddWithValue("@developerID", DeveloperCombo.SelectedValue);
    cmd.Parameters.AddWithValue("@publisherID", PublisherCombo.SelectedValue);
    cmd.Parameters.AddWithValue("@consoleID", ConsoleCombo.SelectedValue);
    var result = cmd.ExecuteNonQuery();
    ...
}

As far as the dateAdded column is concerned I would simply remove it from the INSERT and add it a default value directly in the SQL database.

Notice how you are directly passing DateTime instances and you leave ADO.NET handle the formats. As a bonus your code is safe against SQL injections.


DateReleasedDate.Value.ToString("yyyy-MM-dd");


The problem is you put GETDATE() into single-quotes. It is trying to convert the string 'GETDATE()' into a date.


The best way to pass a date into SQL from .net, IMO, is to use the .ToOADate function.

The function passes in a numerical representation of the date that will work on any database datetime \ date field regardless of the regional setup.

Some info for you: ToOADate

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜