package main import ( "database/sql" "encoding/csv" "flag" "log" "os" "strconv" _ "github.com/go-sql-driver/mysql" ) // Student from Database type Student struct { Vorname, Nachname string Matrikelnummer int StudiengangID int } var ( databaseURL = flag.String("db", "julian:hi@/test", "The Database url") ) const ( insertQuery = "INSERT INTO Teilnehmer (Nachname, Vorname, Matrnr, Studiengang) VALUES(?,?,?,?)" ) // Main Function func main() { flag.Parse() if flag.NArg() == 0 { log.Fatal("no file(s) given!") } // try to open file file, err := os.Open(flag.Arg(0)) if err != nil { log.Fatal("could not open file:", err) } defer file.Close() reader := csv.NewReader(file) defer log.Println("shutdown completed") // list all Database providers log.Println("Database providers:", sql.Drivers()) // connect to database db, err := sql.Open("mysql", *databaseURL) if err != nil { log.Fatal(err) } defer db.Close() log.Println("mysql connection established") // prepare Queries newStudent, err := db.Prepare(insertQuery) if err != nil { log.Fatal("Error preparing statement:", insertQuery+":", err) } defer newStudent.Close() // init completed defer log.Println("shutting down") var ( line []string linenumber = 0 count = 0 ) for ; err == nil; line, err = reader.Read() { linenumber++ if len(line) < 4 { log.Println("line", linenumber, "malformed") continue } number, err := strconv.Atoi(line[2]) if err != nil { log.Println("line", linenumber, ":could not convert ID:"+line[2]+":", err) continue } if number < 0 { log.Println("line", linenumber, ":ID invalid:", number) continue } studiengang, err := strconv.Atoi(line[3]) if err != nil { log.Println("line", linenumber, ":studiengang could not be converted:", err) continue } if studiengang < 0 || studiengang > 2 { log.Println("line", linenumber, ":Studiengang does not exist:", studiengang) continue } if _, err := newStudent.Exec(line[0], line[1], number, studiengang); err != nil { log.Println("line", linenumber, ":could not execute INSERT:", err) continue } count++ } log.Println("done, inserted", count, "records") }