Golang中如何向SQL表插入数据
Golang中如何向SQL表插入数据
import (
"log"
"io/ioutil"
"go/scanner"
"os"
"bufio"
"strings"
"strconv"
"fmt"
"time"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func init() {
var err error
db,err = sql.Open("mysql","root1:root1@tcp(localhost:3306)/lgforusage?charset=utf8")
if err != nil{
panic(err)
}
if err = db.Ping(); err != nil {
panic(err)
}
fmt.Println("You connected to your database")
}
func ReadFiles(locationPath string) (string,error) {
var lines string
folder, err := ioutil.ReadDir(locationPath)
if err != nil {
log.Fatal(err)
//return nil,err
}
for _, f := range folder {
file, err := os.Open(locationPath+f.Name())
//lines ,err := ioutil.ReadFile(locationPath+f.Name())
if err != nil {
log.Fatal(err)
//return nil,err
}
var sb strings.Builder
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line:= scanner.Text()
sb.WriteString(line)
sb.WriteString(",")
}
lines = strings.TrimSuffix(sb.String(),",")
linejoin := strings.Join(strings.Fields(lines),"")
readline(linejoin)
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
return lines,scanner.Error{}
}
func readline( liness string ) {
s :=strings.Split(liness,",")
locationname,mac,forgusage,loadingtime,fgusage,enusage,ossidusage,boingousage,landlineusage,uptime,restrouter:=s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10]
fgusagesplit := strings.Split(forgusage,"MB")
fgusagesplitvaltest :=fgusagesplit[0]
fguintval,err := strconv.ParseInt(fgusagesplitvaltest, 10, 64)
if err != nil{
fmt.Println("ForGUsage not compatibe null")
}
fmt.Printf("%T\n", fguintval)
//LoadingTime1,err := time.Parse("Jan-02-2006",LoadingTime)
//if err != nil{
// //panic(err)
// fmt.Println("Time Convert Error")
//}
fgusageval,err := strconv.ParseInt(fgusage,10,32)
if err != nil{
fmt.Println("FourGUsage cannot be null")
}
enusageval,err := strconv.ParseInt(enusage,10,32)
if err !=nil{
fmt.Println("Ethanet useage cannot be null")
}
ossidusageval,err := strconv.ParseInt(ossidusage,10,32)
if err != nil{
fmt.Println("OOP Meadia value cannot be null")
}
boingousageval,err := strconv.ParseInt(boingousage,10,32)
if err != nil{
fmt.Println("BoingoUsage value cannot be null")
}
landlineusageval,err := strconv.ParseInt(landlineusage,10,32)
if err != nil{
fmt.Println("LandLineUsage value cannot be null")
}
restrouterval,err :=strconv.ParseInt(restrouter,10,32)
if err != nil{
fmt.Println("reset value not display")
}
dt:= time.Now()
systemtime:= dt.Format("01-02-2006 15:04:05")
//UpTimeVal,err := time.Parse("2006-06-02",UpTime)
//if err != nil{
// fmt.Println("UpTime value cannot bernull")
//}
fmt.Println("LocationName = ",locationname)
fmt.Println("Mac =",mac)
fmt.Println("FourGUsage =",fguintval)
fmt.Println("LoadingTime =",loadingtime)
fmt.Println("FGUsage =",fgusageval)
fmt.Println("ENUsage =",enusageval)
fmt.Println("OSSIDUsage =",ossidusageval)
fmt.Println("BoingoUsage = ",boingousageval)
fmt.Println("LandLineUsage =",landlineusageval)
fmt.Println("UpTime =",uptime)
fmt.Println("restrouter",restrouterval)
fmt.Println(systemtime)
_,err =db.Exec("insert into forgtb(locationname,mac,fgintval,loadingtime,fgusageval,enusageval,ossidusageval,boingousageval,landlineusageval,uptime,resetrouterval,systemtime)values ('$1','$2',fgintval,'$4',fgusageval,enusageval,ossidusageval,boingousageval,landlineusageval,'$10',resetrouterval,systemtime)")
if err!= nil{
panic(err)
fmt.Println("insert query not working",err.Error())
}
}
func main() {
var locationPath ="E:/"
ReadFiles(locationPath)
}
当我运行此函数时,所有值都为空。我已附上我的代码,请帮忙修正。
数据库输出结果:
| locationname | mac | fgintval | loadingtime | fgusageval | enusageval | ossidusageval | boingousageval | landlineusageval | uptime | resetrouterval | systemtime |
|---|---|---|---|---|---|---|---|---|---|---|---|
| $1 | $2 | NULL | $4 | NULL | NULL | NULL | NULL | NULL | $10 | NULL | NULL |
更多关于Golang中如何向SQL表插入数据的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
@sudesh 你能用三个反引号包裹你的代码,或者把它发布到 Go Playground 上吗?
这里有一个关于代码块使用的链接;在这里使用三个反引号的方式是相同的:https://help.github.com/en/articles/creating-and-highlighting-code-blocks
更多关于Golang中如何向SQL表插入数据的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在您的代码中,插入SQL语句使用了错误的占位符语法,并且没有正确绑定变量值。Go的database/sql包使用?作为占位符(MySQL),而不是$1、$2等。以下是修正后的readline函数:
func readline(liness string) {
s := strings.Split(liness, ",")
if len(s) < 11 {
fmt.Println("Insufficient data fields")
return
}
locationname, mac, forgusage, loadingtime, fgusage, enusage, ossidusage, boingousage, landlineusage, uptime, restrouter := s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10]
// 解析 fgintval
fgusagesplit := strings.Split(forgusage, "MB")
var fguintval int64
if len(fgusagesplit) > 0 && fgusagesplit[0] != "" {
var err error
fguintval, err = strconv.ParseInt(fgusagesplit[0], 10, 64)
if err != nil {
fmt.Println("ForGUsage not compatible, using 0")
fguintval = 0
}
}
// 解析其他整数字段
fgusageval, err := strconv.ParseInt(fgusage, 10, 32)
if err != nil {
fmt.Println("FourGUsage cannot be null, using 0")
fgusageval = 0
}
enusageval, err := strconv.ParseInt(enusage, 10, 32)
if err != nil {
fmt.Println("Ethernet usage cannot be null, using 0")
enusageval = 0
}
ossidusageval, err := strconv.ParseInt(ossidusage, 10, 32)
if err != nil {
fmt.Println("OSSID usage value cannot be null, using 0")
ossidusageval = 0
}
boingousageval, err := strconv.ParseInt(boingousage, 10, 32)
if err != nil {
fmt.Println("BoingoUsage value cannot be null, using 0")
boingousageval = 0
}
landlineusageval, err := strconv.ParseInt(landlineusage, 10, 32)
if err != nil {
fmt.Println("LandLineUsage value cannot be null, using 0")
landlineusageval = 0
}
restrouterval, err := strconv.ParseInt(restrouter, 10, 32)
if err != nil {
fmt.Println("Reset value not valid, using 0")
restrouterval = 0
}
dt := time.Now()
systemtime := dt.Format("2006-01-02 15:04:05")
// 修正的插入语句,使用 ? 占位符并正确传递参数
_, err = db.Exec("INSERT INTO forgtb (locationname, mac, fgintval, loadingtime, fgusageval, enusageval, ossidusageval, boingousageval, landlineusageval, uptime, resetrouterval, systemtime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
locationname, mac, fguintval, loadingtime, fgusageval, enusageval, ossidusageval, boingousageval, landlineusageval, uptime, restrouterval, systemtime)
if err != nil {
fmt.Println("Insert query failed:", err.Error())
return
}
fmt.Println("Data inserted successfully")
}
主要修改点:
- 将SQL语句中的
$1、$2等占位符改为? - 在
db.Exec调用中按顺序传递所有参数值 - 添加了字段数量检查,防止数组越界
- 改进了错误处理,为解析失败的字段提供默认值0
- 修正了时间格式为标准的MySQL日期时间格式
- 添加了插入成功的确认消息
确保您的数据库表forgtb的列定义与插入的数据类型匹配。特别是fgintval、fgusageval等整数字段应该定义为适当的整数类型(如INT、BIGINT等)。

