英文:
Golang: Mysql Prepare Insert statements do not add rows into db table
问题
所以我正在尝试使用一个MySQL驱动程序将数据插入数据库。
具体来说,我正在使用这个驱动程序:
"github.com/go-sql-driver/mysql"
这是我的代码
func main() {
db, err := sql.Open("mysql", "psanker:123@/education_data")
err = db.Ping()
if err != nil {
fmt.Println("Failed to prepare connection to database")
log.Fatal("Error:", err.Error())
}
defer db.Close()
content, err := ioutil.ReadFile("activities.csv")
lines := strings.Split(string(content), "\r")
//only work so long as I have one district
rows, err := db.Query("SELECT id FROM districts")
var districtId int
defer rows.Close()
for rows.Next() {
err := rows.Scan(&districtId)
check(err)
}
for i, line := range lines {
if i > 1 {
splitStr := strings.Split(line, ",")
var activityCode string
if strings.Contains(splitStr[0], "-") {
//this is an activity
activityCode = splitStr[0]
stmt1, _ := db.Prepare("INSERT INTO activities(code) VALUES(?)")
stmt2, _ := db.Prepare("INSERT INTO activities(name) VALUES(?)")
res, _ := stmt1.Exec(splitStr[0])
stmt2.Exec(splitStr[1])
} else {
//this is a sub activity
stmt1, _ := db.Prepare("INSERT INTO sub_activities(code) VALUES(?)")
stmt2, _ := db.Prepare("INSERT INTO sub_activities(name) VALUES(?)")
stmt1.Exec(splitStr[0])
stmt2.Exec(splitStr[1])
if activityCode != "" {
rows, _ := db.Query("SELECT id from activities where code = ?", activityCode)
var activityId int
for rows.Next() {
err := rows.Scan(&activityId)
check(err)
stmt3, err := db.Prepare("INSERT INTO sub_activities(activity_id) VALUES(?)")
stmt3.Exec(activityId)
}
}
rows, _ := db.Query("SELECT id from sub_activities where code= ?", splitStr[0])
var sub_activityId int
for rows.Next() {
err := rows.Scan(&sub_activityId)
check(err)
stmt5, _ := db.Prepare("INSERT INTO sub_activity_expenditure(district_id) VALUES(?)")
stmt6, _ := db.Prepare("INSERT INTO sub_activity_expenditure(sub_activity_id) VALUES(?)")
stmt7, _ := db.Prepare("INSERT INTO sub_activity_expenditure(expenditure) VALUES(?)")
stmt5.Exec(districtId)
stmt6.Exec(sub_activityId)
stmt7.Exec(splitStr[2])
}
}
}
}
}
当我检查MySQL数据库时,表中没有插入任何行。我认为我正在访问正确的数据库,因为从districts获取id的初始查询返回1,这是正确的。
发生了什么?
编辑
我通过执行以下操作确认我在正确的数据库中
rows, err = db.Query("SELECT DATABASE();")
var test string
for rows.Next() {
rows.Scan(&test)
fmt.Println(test)
}
它打印出 education_data
英文:
So I'm trying to use a mysql driver to insert data into a database.
Specifically, I'm using this one:
"github.com/go-sql-driver/mysql"
This is my code
func main() {
db, err := sql.Open("mysql", "psanker:123@/education_data")
err = db.Ping()
if err != nil {
fmt.Println("Failed to prepare connection to database")
log.Fatal("Error:", err.Error())
}
defer db.Close()
content, err := ioutil.ReadFile("activities.csv")
lines := strings.Split(string(content), "\r")
//only work so long as I have one district
rows, err := db.Query("SELECT id FROM districts")
var districtId int
defer rows.Close()
for rows.Next() {
err := rows.Scan(&districtId)
check(err)
}
for i, line := range lines {
if i > 1 {
splitStr := strings.Split(line, ",")
var activityCode string
if strings.Contains(splitStr[0], "-") {
//this is an activity
activityCode = splitStr[0]
stmt1, _ := db.Prepare("INSERT INTO activities(code) VALUES(?)")
stmt2, _ := db.Prepare("INSERT INTO activities(name) VALUES(?)")
res, _ := stmt1.Exec(splitStr[0])
stmt2.Exec(splitStr[1])
} else {
//this is a sub activity
stmt1, _ := db.Prepare("INSERT INTO sub_activities(code) VALUES(?)")
stmt2, _ := db.Prepare("INSERT INTO sub_activities(name) VALUES(?)")
stmt1.Exec(splitStr[0])
stmt2.Exec(splitStr[1])
if activityCode != "" {
rows, _ := db.Query("SELECT id from activities where code = ?", activityCode)
var activityId int
for rows.Next() {
err := rows.Scan(&activityId)
check(err)
stmt3, err := db.Prepare("INSERT INTO sub_activities(activity_id) VALUES(?)")
stmt3.Exec(activityId)
}
}
rows, _ := db.Query("SELECT id from sub_activities where code= ?", splitStr[0])
var sub_activityId int
for rows.Next() {
err := rows.Scan(&sub_activityId)
check(err)
stmt5, _ := db.Prepare("INSERT INTO sub_activity_expenditure(district_id) VALUES(?)")
stmt6, _ := db.Prepare("INSERT INTO sub_activity_expenditure(sub_activity_id) VALUES(?)")
stmt7, _ := db.Prepare("INSERT INTO sub_activity_expenditure(expenditure) VALUES(?)")
stmt5.Exec(districtId)
stmt6.Exec(sub_activityId)
stmt7.Exec(splitStr[2])
}
}
}
}
}
When I check Mysql database, there are no rows inserted into the tables. I think I'm accessing the right database because the initial query that gets id from districts is returning 1, which is correct.
What's going on?
EDIT
I have confirmed I'm in the right db by doing this
rows, err = db.Query("SELECT DATABASE();")
var test string
for rows.Next() {
rows.Scan(&test)
fmt.Println(test)
}
Which prints out education_data
答案1
得分: 1
由于您尝试插入表格时,我在聊天中提醒您,您的列是非空的,而您实际上是要创建一行,但却创建了两行。stmt1
和stmt2
失败是因为没有为非空列提供参数,以便插入成功所需的所有数据。
请专注于为stmt1
和stmt2
创建一行(将它们合并为一个带有2个参数的单个stmt1
来执行)。
确保字符串用单引号括起来。
英文:
As you are trying to insert into a table, I was reminded (in chat at least) that your columns are non-null and you really meant to create one row when you were in fact creating two. It failed on stmt1
and stmt2
because non-nullable columns were not given parameters to replace for all necessary data for insertion to succeed.
Focus on creating one row for stmt1
and stmt2
(combine them into a single stmt1
to execute with 2 parameters).
Make sure strings are wrapped with a single quote.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论