package main import ( "bufio" "database/sql" "encoding/csv" "flag" "fmt" "log" "os" "strconv" "strings" _ "github.com/go-sql-driver/mysql" ) var ( dbURL = flag.String("db", "julian:hi@/test", "The Database") ) const ( queryInsert = "INSERT INTO Punkte (Matrnr, Aufgabe, Punkte) VALUES(?,?,?)" ) // This function assumes it input to be only one float func convertFloat(input string) string { // replace all , with . return strings.Replace(input, ",", ".", -1) } func YesNo() bool { reader := bufio.NewReader(os.Stdin) for { line, _, err := reader.ReadLine() if err != nil { return false } // default case if len(line) == 0 { return true } switch line[0] { case 'Y': fallthrough case 'y': return true case 'N': fallthrough case 'n': return false } } } func main() { flag.Parse() files := flag.Args() if len(files) == 0 { log.Fatal("no files given!") } db, err := sql.Open("mysql", *dbURL) if err != nil { log.Fatal("error connecting to Database:", err) } defer db.Close() for _, f := range files { log.Println("importing", f) file, err := os.Open(f) if err != nil { log.Println("could not open file:", f+":", err) continue } reader := csv.NewReader(file) transaction, err := db.Begin() if err != nil { log.Fatal("cannot prepare statement:", err) } stmt, err := transaction.Prepare(queryInsert) if err != nil { log.Fatal("could not prepare insert statement:", err) } defer stmt.Close() var ( line []string count = 0 linecount = 0 ID int Aufgabe = 1 points float64 ) for { linecount++ line, err = reader.Read() if err != nil || line == nil { break } if len(line) < 2 { log.Println(linecount, ": malformed line") continue } if ID, err = strconv.Atoi(line[0]); err != nil { log.Println(linecount, ": no ID given, could not convert:", err) continue } fmt.Print(ID, " ") Aufgabe = 1 for _, p := range line[1:] { if points, err = strconv.ParseFloat(convertFloat(p), 32); err != nil { log.Println(linecount, "A", Aufgabe, ": could not parse points:", err) } fmt.Print(points, " ") if _, err = stmt.Exec(ID, Aufgabe, points); err != nil { log.Println(linecount, ": error inserting:", err) } Aufgabe++ } fmt.Println() count++ } fmt.Println("read", count, "Students") fmt.Println("commit changes? (Y/n)") if YesNo() { transaction.Commit() } } }