2018-04-20 15:49
浏览 283

使用golang将DateTime值插入MS SQL

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

CREATE TABLE dbo.TimeSample (
    ModifiedDate datetime

The golang code I have is this:

func timeSample(db *sql.DB) (error) {
    ctx := context.Background()
    var err error

    t := time.Now().Format(time.RFC3339)
    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


    return nil

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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用golang将DateTime值插入MS SQL表中。 SQL表的结构如下:

 ModifiedDate datetime 
 <  p>我拥有的golang代码是这样的: 
  func timeSample(db * sql.DB)(错误){
 ctx:= context.Background()
 var 错误错误
t:= time.Now()。Format(time.RFC3339)
 tsql:= fmt.Sprintf(“ INSERT INTO [dbo]。[TimeSample]([ModifiedDate  ])VALUES('%s');“,time.Now()。Format(time.RFC3339))
结果,错误:= db.ExecContext(ctx,tsql)  
 if err!= nil {
 log.Fatal(“插入新行时出错:” + err.Error())
返回 nil 


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

关于我应该如何做的任何想法 ormat这可以用于MS SQL吗?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtwk6019 2018-04-20 16:18

    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:

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

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

    解决 无用
    打赏 举报

相关推荐 更多相似问题