84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"flag"
|
|
"log"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
)
|
|
|
|
var (
|
|
dbURL = flag.String("db", "julian:hi@/test", "Die URL zur Datenbank")
|
|
table = flag.String("table", "Teilnehmer", "Die Tabelle")
|
|
key = flag.String("key", "Matrnr", "Der Tabellenschlüsselname")
|
|
attr = flag.String("attr", "Nachname", "Die Spalte zum Cleanen")
|
|
)
|
|
|
|
const (
|
|
querySelect = "SELECT ?,? FROM ?"
|
|
queryUpdate = "UPDATE ? SET ?=? WHERE ?=?"
|
|
)
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
|
|
db, err := sql.Open("mysql", *dbURL)
|
|
if err != nil {
|
|
log.Fatal("error connecting to database:", err)
|
|
}
|
|
defer db.Close()
|
|
|
|
statement, err := db.Prepare("SELECT " + *key + "," + *attr + " FROM " + *table)
|
|
|
|
if err != nil {
|
|
log.Fatal("error in precompiled statement:", querySelect+":", err)
|
|
}
|
|
defer statement.Close()
|
|
|
|
rows, err := statement.Query()
|
|
|
|
if err != nil {
|
|
log.Fatal("error executing query:", err)
|
|
}
|
|
|
|
context, err := db.Begin()
|
|
if err != nil {
|
|
log.Fatal("error creating context:", err)
|
|
}
|
|
|
|
update, err := context.Prepare("UPDATE " + *table + " SET " + *attr + "=? WHERE " + *key + "=?")
|
|
if err != nil {
|
|
log.Fatal("error in precompiled statement:", queryUpdate+":", err)
|
|
}
|
|
|
|
var (
|
|
keyBuffer int
|
|
dirty, clean string
|
|
|
|
count int
|
|
)
|
|
|
|
for rows.Next() {
|
|
if err = rows.Scan(&keyBuffer, &dirty); err != nil {
|
|
log.Println("error while reading:", err)
|
|
}
|
|
|
|
clean = strip(dirty)
|
|
if clean != dirty {
|
|
if result, err := update.Exec(clean, keyBuffer); err != nil {
|
|
log.Fatal("error on update, change canceled:", err)
|
|
} else if i, err := result.RowsAffected(); err == nil && i != 1 {
|
|
log.Fatal("changed to many rows... aborting")
|
|
} else {
|
|
count++
|
|
}
|
|
}
|
|
}
|
|
|
|
log.Println("committing change,", count, "rows affected")
|
|
if err := context.Commit(); err != nil {
|
|
log.Println("could not commit changed:", err)
|
|
}
|
|
}
|