2 回答
TA贡献1934条经验 获得超2个赞
您将记录从以下行扫描到Incident_Number, Last_Resolved_Date,中:Corporate_ID
err := rows.Scan(&Incident_Number, &Last_Resolved_Date, &Corporate_ID)
但是你在Exec()函数中传递了不同的参数。您必须传递扫描变量才能将记录插入到不同的数据库表中。
stmt1, err := db1.Prepare("INSERT INTO mdesk.dbo.tbl_tcktinfo(TicketNumber, ResolvedDate, CDSID) VALUES(?,?,?)")
if err != nil {
log.Fatal(err)
}
defer stmt1.Close() // always clean up after yourself, preferably return errors here, too
for rows.Next() {
err := rows.Scan(&Incident_Number, &Last_Resolved_Date, &Corporate_ID)
if err != nil {
log.Fatal(err)
}
res, err := stmt1.Exec(Incident_Number, Last_Resolved_Date, Corporate_ID)
if err != nil {
log.Println(err)
}
log.Println(Incident_Number, Last_Resolved_Date, Corporate_ID)
}
TA贡献1848条经验 获得超6个赞
添加到已接受的答案:我建议您多做一些事情以确保一致性,并更“负责任地”处理您的资源。你正在关闭你的数据库连接,当然,但我会养成以几乎相同的方式处理其他资源的习惯。
此外,如果中途出现问题,我强烈建议您将插入包装到事务中,而不是必须截断表并重新启动进程:
defer rows.Close() // close your rows resource
defer db1.Close() // close at the very end
tx, err := db1.BeginTx(context.Background(), nil) // pass in a context with timeout or some other cancelable context if needed
if err != nil {
return err // I'm returning, you can do as you like with this
}
stmt, err := tx.Prepare("INSERT INTO ...") // create the statement once
defer stmt.Close() // add to defer stack
for rows.Next() {
// instead of your Camel_Snake_Cased vars, I'm using the preferred style and camelCase your var names instead...
if err := rows.Scan(&incidentNumber, &lastResolvedDate, &corporateID); err != nil {
tx.Rollback() // rollback transaction
return err
}
if err := stmt.Exec(incidentNumber, lastResolvedDate, corporateID); err != nil {
tx.Rollback() // again, rollback...
return err
}
}
if err := tx.Commit(); err !≃ nil {
tx.Rollback() // not needed, but I add it as a habit
return err
}
return nil
现在重要的是要注意所有这些Close()函数和tx.Rollback()调用都返回错误。最好至少将它们包装在日志调用中,如下所示:
log.Printf("Rolling back: %+v", tx.Rollback())
// and
log.Printf("Closing DB/ROWS/STMT: %+v", db1.Close()) // same for rows, stmt etc..
- 2 回答
- 0 关注
- 89 浏览
添加回答
举报