course/mysql/sql_inject.go

62 lines
1.0 KiB
Go

package main
import (
"fmt"
"github.com/jmoiron/sqlx"
"log"
_ "github.com/go-sql-driver/mysql"
)
var c *sqlx.DB
type user23 struct {
ID int
NAME string
AGE int
}
// sql 注入
func main() {
err := connect()
if err != nil {
return
}
sqlInject("王奥")
//拼接之后会查出所有数据
sqlInject("xxx' or 1=1 #")
}
func sqlInject(name string) {
sqlStr := fmt.Sprintf("select id,name,age from user where name='%v'", name)
fmt.Println("sql:", sqlStr)
var u []user23
err := c.Select(&u, sqlStr)
if err != nil {
log.Fatal(err)
return
}
for _, user1 := range u {
fmt.Println("user1:", user1)
}
}
func connect() (err error) {
c, err = sqlx.Connect("mysql", "root:123456@tcp(43.143.245.135:3306)/user")
if err != nil {
log.Println(err)
return err
}
//connect方法提供了ping。所以不需要ping
//err = databasE.Ping()
//if err != nil {
// log.Println(err)
// return err
//}
log.Println("Successfully connected to mysql")
c.SetMaxOpenConns(10)
c.SetMaxIdleConns(5)
return nil
}