所以我试图使用 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() } } } }}当我检查 Mysql 数据库时,表中没有插入任何行。我想我正在访问正确的数据库,因为从地区获取 id 的初始查询返回 1,这是正确的。这是怎么回事?编辑我已经通过这样做确认我在正确的数据库中rows, err = db.Query("SELECT DATABASE();")var test stringfor rows.Next() { rows.Scan(&test) fmt.Println(test)}哪个打印出来 education_data
1 回答
- 1 回答
- 0 关注
- 341 浏览
添加回答
举报
0/150
提交
取消