我正在尝试使用golang将DateTime值插入到MS SQL表中。 SQL表是这种结构:

我拥有的golang代码是这样的:

尝试插入时出现以下错误:

2018-04-20T10:39:30-05:00 2018/04/20 10:39:30插入新行时出错:mssql:从字符串转换日期和/或时间时转换失败。 退出状态1

任何关于如何格式化MS SQL的想法?


I am trying to insert a DateTime value into a MS SQL table using golang. The SQL table is this structure:

The golang code I have is this:

I am getting the following error when trying to insert:

2018-04-20T10:39:30-05:00 2018/04/20 10:39:30 Error inserting new row: mssql: Conversion failed when converting date and/or time from character string. exit status 1

Any idea on how I should format this to work for MS SQL?

CREATE TABLE dbo.TimeSample (
    ModifiedDate datetime
);
func timeSample(db *sql.DB) (error) {
    ctx := context.Background()
    var err error

    t := time.Now().Format(time.RFC3339)
    fmt.Println(t)
    tsql := fmt.Sprintf("INSERT INTO [dbo].[TimeSample] ([ModifiedDate]) VALUES ('%s');",time.Now().Format(time.RFC3339))

    // Execute non-query
    result, err := db.ExecContext(ctx, tsql)
    if err != nil {
        log.Fatal("Error inserting new row: " + err.Error())
        return err
    }

    fmt.Println(result)

    return nil
}
CREATE TABLE dbo.TimeSample (
    ModifiedDate datetime
);
func timeSample(db *sql.DB) (error) {
    ctx := context.Background()
    var err error

    t := time.Now().Format(time.RFC3339)
    fmt.Println(t)
    tsql := fmt.Sprintf("INSERT INTO [dbo].[TimeSample] ([ModifiedDate]) VALUES ('%s');",time.Now().Format(time.RFC3339))

    // Execute non-query
    result, err := db.ExecContext(ctx, tsql)
    if err != nil {
        log.Fatal("Error inserting new row: " + err.Error())
        return err
    }

    fmt.Println(result)

    return nil
}

为了详细说明我的评论,你应该做的是使用参数化SQL - 它不仅将时间值转换为正确的格式,而且还保护了SQL注入攻击。 通常SQL参数表示为? 但有些驱动程序使用$1:name因此请检查驱动程序的文档。 然后你的代码会像这样:

请注意,你不想终止; 也在SQL字符串中。


To elaborate on my comment, what you should do is to use parametrized SQL - it not only takes care of converting time values to correct format it also protects agains SQL injection attack. Usually SQL parameters are represented by ? but some drivers use $1 or :name so check the driver's documentation. And your code would then be like:

Note that you don't want to have terminating ; in the SQL string too.

tsql := "INSERT INTO [dbo].[TimeSample] ([ModifiedDate]) VALUES (?)"
result, err := db.ExecContext(ctx, tsql, time.Now())
tsql := "INSERT INTO [dbo].[TimeSample] ([ModifiedDate]) VALUES (?)"
result, err := db.ExecContext(ctx, tsql, time.Now())

相关问答