如果Textbox为空,则在SQL中将datetime字段设置为NULL

tec*_*ora 4 c# sql

如果文本框为空,尝试将SQL表中的日期时间字段设置为NULL,我似乎无法使其工作.

        string EndDate = "";
        if (String.IsNullOrEmpty(EndDateTxtBox.Text.Trim()))
        {
            EndDate = null;
        }
        else
        {
            EndDate = EndDateTxtBox.Text;
        }

        var sql = String.Format(@"UPDATE Test SET StartDate='{0}', 
                                 EndDate='{1}' WHERE ID = '{2}'",
                                 StartDateTxtBox.Text, EndDate, id);
Run Code Online (Sandbox Code Playgroud)

当我这样做并提出一个断点时,我得到了"var sql":

"UPDATE Test SET StartDate='5/23/2013', EndDate=" WHERE ID = '19'"
Run Code Online (Sandbox Code Playgroud)

我尝试从sql字符串中删除'但是这也不起作用.有什么建议?

编辑:我理解防止SQL注入的重要性,但这是我内部Web服务器上的一个页面,仅供我使用而不是向公众投射.这是为了帮助我跟踪个人事物.

Mar*_*ell 12

参数.

首先,您应该将UI代码从数据库代码中移开,这样当它到达数据库附近时,我们就能正确输入数据.例如:

void UpdateDates(int id, DateTime startDate, DateTime? endDate) {...}
Run Code Online (Sandbox Code Playgroud)

并在调用者处放置Parse您想要的任何代码- 而不是在数据库附近.现在我们需要实现:

void UpdateDates(int id, DateTime startDate, DateTime? endDate) {
    //... where-ever cmd comes from, etc
    cmd.CommandText =
        "update Test set StartDate=@start, EndDate=@end where ID = @id";
    cmd.Parameters.AddWithValue("id", id);
    cmd.Parameters.AddWithValue("start", startDate);
    cmd.Parameters.AddWithValue("end", (object)endDate ?? DBNull.Value);
    cmd.ExecuteNonQuery();
    // ... cleanup etc
}
Run Code Online (Sandbox Code Playgroud)

或者像"小巧玲珑"这样的工具:

void UpdateDates(int id, DateTime startDate, EndDate? endDate) {
    //... where-ever connection comes from, etc
    connection.Execute(
        "update Test set StartDate=@start, EndDate=@end where ID = @id",
        new { id, start = startDate, end = endDate}); // painfully easy
    // ... cleanup etc
}
Run Code Online (Sandbox Code Playgroud)