Example #1
0
func main() {
	user := "******"
	pass := "******"
	dbname := "test"
	//proto  := "unix"
	//addr   := "/var/run/mysqld/mysqld.sock"
	proto := "tcp"
	addr := "127.0.0.1:3306"

	db := mysql.New(proto, "", addr, user, pass, dbname)

	fmt.Printf("Connect to %s:%s... ", proto, addr)
	checkError(db.Connect())
	printOK()

	fmt.Print("Drop A table if exists... ")
	_, err := db.Start("drop table A")
	if err == nil {
		printOK()
	} else if e, ok := err.(*mysql.Error); ok {
		// Error from MySQL server
		fmt.Println(e)
	} else {
		checkError(err)
	}

	fmt.Print("Create A table... ")
	checkedResult(db.Query("create table A (name varchar(40), number int)"))
	printOK()

	fmt.Print("Prepare insert statement... ")
	ins, err := db.Prepare("insert A values (?, ?)")
	checkError(err)
	printOK()

	fmt.Print("Prepare select statement... ")
	sel, err := db.Prepare("select * from A where number > ? or number is null")
	checkError(err)
	printOK()

	params := struct {
		txt    *string
		number *int
	}{}

	fmt.Print("Bind insert parameters... ")
	ins.Bind(&params)
	printOK()

	fmt.Print("Insert into A... ")
	for ii := 0; ii < 1000; ii += 100 {
		if ii%500 == 0 {
			// Assign NULL values to the parameters
			params.txt = nil
			params.number = nil
		} else {
			// Modify parameters
			str := fmt.Sprintf("%d*10= %d", ii/100, ii/10)
			params.txt = &str
			params.number = &ii
		}
		// Execute statement with modified data
		_, err = ins.Run()
		checkError(err)
	}
	printOK()

	fmt.Println("Select from A... ")
	rows, res := checkedResult(sel.Exec(0))
	name := res.Map("name")
	number := res.Map("number")
	for ii, row := range rows {
		fmt.Printf(
			"Row: %d\n name:  %-10s {%#v}\n number: %-8d  {%#v}\n", ii,
			"'"+row.Str(name)+"'", row[name],
			row.Int(number), row[number],
		)
	}

	fmt.Print("Remove A... ")
	checkedResult(db.Query("drop table A"))
	printOK()

	fmt.Print("Close connection... ")
	checkError(db.Close())
	printOK()
}
Example #2
0
func main() {
	user := "******"
	pass := "******"
	dbname := "test"
	//proto  := "unix"
	//addr   := "/var/run/mysqld/mysqld.sock"
	proto := "tcp"
	addr := "127.0.0.1:3306"

	db := mysql.New(proto, "", addr, user, pass, dbname)
	//db.Debug = true

	fmt.Printf("Connect to %s:%s... ", proto, addr)
	checkError(db.Connect())
	printOK()

	fmt.Print("Drop 'web' table if exists... ")
	_, err := db.Start("DROP TABLE web")
	if err == nil {
		printOK()
	} else if e, ok := err.(*mysql.Error); ok {
		// Error from MySQL server
		fmt.Println(e)
	} else {
		checkError(err)
	}

	fmt.Print("Create 'web' table... ")
	_, err = db.Start("CREATE TABLE web (url VARCHAR(80), content LONGBLOB)")
	checkError(err)
	printOK()

	fmt.Print("Prepare insert statement... ")
	ins, err := db.Prepare("INSERT INTO web VALUES (?, ?)")
	checkError(err)
	printOK()

	fmt.Print("Prepare select statement... ")
	sel, err := db.Prepare("SELECT url, OCTET_LENGTH(content) FROM web")
	checkError(err)
	printOK()

	var url string

	fmt.Print("Bind insert parameters... ")
	ins.Bind(&url, []byte(nil))
	printOK()

	fmt.Println()
	for {
		url = ""
		fmt.Print("Please enter an URL (blank line terminates input): ")
		fmt.Scanln(&url)
		if len(url) == 0 {
			break
		}
		if !strings.Contains(url, "://") {
			url = "http://" + url
		}
		http_res, err := http.Get(url)
		if err != nil {
			fmt.Println(err)
			continue
		}
		// Retrieve response directly into database. Use 8 kB buffer.
		checkError(ins.SendLongData(1, http_res.Body, 8192))
		_, err = ins.Run()
		checkError(err)
	}
	fmt.Println()

	fmt.Print("Select from 'web' table... ")
	rows, res, err := sel.Exec()
	checkError(err)
	printOK()

	// Print fields names
	fmt.Println()
	for _, field := range res.Fields() {
		fmt.Printf("%-38s ", field.Name)
	}
	fmt.Println()
	fmt.Println("------------------------------------------------------------")

	// Print result
	for _, row := range rows {
		for ii, col := range row {
			if col == nil {
				fmt.Print("%-38s ", "NULL")
			} else {
				fmt.Printf("%-38s ", row.Bin(ii))
			}
		}
		fmt.Println()
	}
	fmt.Println()

	fmt.Print("Hit ENTER to exit ")
	fmt.Scanln()

	fmt.Print("Remove 'web' table... ")
	_, err = db.Start("DROP TABLE web")
	checkError(err)
	printOK()

	fmt.Print("Close connection... ")
	checkError(db.Close())
	printOK()
}
Example #3
0
// Open new connection. The uri need to have the following syntax:
//
//   [PROTOCOL_SPECFIIC*]DBNAME/USER/PASSWD
//
// where protocol spercific part may be empty (this means connection to
// local server using default protocol). Currently possible forms:
//
//   DBNAME/USER/PASSWD
//   unix:SOCKPATH*DBNAME/USER/PASSWD
//   unix:SOCKPATH,OPTIONS*DBNAME/USER/PASSWD
//   tcp:ADDR*DBNAME/USER/PASSWD
//   tcp:ADDR,OPTIONS*DBNAME/USER/PASSWD
//
// OPTIONS can contain comma separated list of options in form:
//   opt1=VAL1,opt2=VAL2,boolopt3,boolopt4
// Currently implemented options:
//   laddr   - local address/port (eg. 1.2.3.4:0)
//   timeout - connect timeout in format accepted by time.ParseDuration
func (d *Driver) Open(uri string) (driver.Conn, error) {
	cfg := *d // copy default configuration
	pd := strings.SplitN(uri, "*", 2)
	if len(pd) == 2 {
		// Parse protocol part of URI
		p := strings.SplitN(pd[0], ":", 2)
		if len(p) != 2 {
			return nil, errors.New("Wrong protocol part of URI")
		}
		cfg.proto = p[0]
		options := strings.Split(p[1], ",")
		cfg.raddr = options[0]
		for _, o := range options[1:] {
			kv := strings.SplitN(o, "=", 2)
			var k, v string
			if len(kv) == 2 {
				k, v = kv[0], kv[1]
			} else {
				k, v = o, "true"
			}
			switch k {
			case "laddr":
				cfg.laddr = v
			case "timeout":
				cfg.timeout = v
			default:
				return nil, errors.New("Unknown option: " + k)
			}
		}
		// Remove protocol part
		pd = pd[1:]
	}
	// Parse database part of URI
	dup := strings.SplitN(pd[0], "/", 3)
	if len(dup) != 3 {
		return nil, errors.New("Wrong database part of URI")
	}
	cfg.db = dup[0]
	cfg.user = dup[1]
	cfg.passwd = dup[2]

	// Establish the connection
	c := conn{mysql.New(
		cfg.proto, cfg.laddr, cfg.raddr, cfg.user, cfg.passwd, cfg.db,
	)}
	if cfg.timeout != "" {
		to, err := time.ParseDuration(cfg.timeout)
		if err != nil {
			return nil, err
		}
		c.my.SetTimeout(to)
	}
	for _, q := range cfg.initCmds {
		c.my.Register(q) // Register initialisation commands
	}
	if err := c.my.Connect(); err != nil {
		return nil, errFilter(err)
	}
	c.my.NarrowTypeSet(true)
	c.my.FullFieldInfo(false)
	return &c, nil
}
Example #4
0
func main() {
	user := "******"
	pass := "******"
	dbname := "test"
	//proto  := "unix"
	//addr   := "/var/run/mysqld/mysqld.sock"
	proto := "tcp"
	addr := "127.0.0.1:3306"

	db := mysql.New(proto, "", addr, user, pass, dbname)

	fmt.Printf("Connect to %s:%s... ", proto, addr)
	checkError(db.Connect())
	printOK()

	fmt.Print("Drop A table if exists... ")
	_, err := db.Start("drop table A")
	if err == nil {
		printOK()
	} else if e, ok := err.(*mysql.Error); ok {
		// Error from MySQL server
		fmt.Println(e)
	} else {
		checkError(err)
	}

	fmt.Print("Create A table... ")
	checkedResult(db.Query("create table A (name varchar(40), number int)"))
	printOK()

	fmt.Print("Insert into A... ")
	for ii := 0; ii < 10; ii++ {
		if ii%5 == 0 {
			checkedResult(db.Query("insert A values (null, null)"))
		} else {
			checkedResult(db.Query(
				"insert A values ('%d*10= %d', %d)", ii, ii*10, ii*100,
			))
		}
	}
	printOK()

	fmt.Println("Select from A... ")
	rows, res := checkedResult(db.Query("select * from A"))
	name := res.Map("name")
	number := res.Map("number")
	for ii, row := range rows {
		fmt.Printf(
			"Row: %d\n name:  %-10s {%#v}\n number: %-8d  {%#v}\n", ii,
			"'"+row.Str(name)+"'", row[name],
			row.Int(number), row[number],
		)
	}

	fmt.Print("Remove A... ")
	checkedResult(db.Query("drop table A"))
	printOK()

	fmt.Print("Close connection... ")
	checkError(db.Close())
	printOK()
}
Example #5
0
func New(proto, laddr, raddr, user, passwd string, db ...string) *Conn {
	return &Conn{
		Raw:        mysql.New(proto, laddr, raddr, user, passwd, db...),
		MaxRetries: 7,
	}
}
Example #6
0
func main() {
	user := "******"
	pass := "******"
	dbname := "test"
	//proto  := "unix"
	//addr   := "/var/run/mysqld/mysqld.sock"
	proto := "tcp"
	addr := "127.0.0.1:3306"

	db := mysql.New(proto, "", addr, user, pass, dbname)

	fmt.Printf("Connect to %s:%s... ", proto, addr)
	checkError(db.Connect())
	printOK()

	fmt.Print("Drop A table if exists... ")
	_, err := db.Start("drop table A")
	if err == nil {
		printOK()
	} else if e, ok := err.(*mysql.Error); ok {
		// Error from MySQL server
		fmt.Println(e)
	} else {
		checkError(err)
	}

	fmt.Print("Create A table... ")
	_, err = db.Start("create table A (name varchar(9), number int) engine=InnoDB")
	checkError(err)
	printOK()

	fmt.Print("Prepare insert statement... ")
	ins, err := db.Prepare("insert A values (?, ?)")
	checkError(err)
	printOK()

	fmt.Print("Prepare select statement... ")
	sel, err := db.Prepare("select * from A")
	checkError(err)
	printOK()

	fmt.Print("Begining a new transaction... ")
	tr, err := db.Begin()
	checkError(err)
	printOK()

	tr_ins := tr.Do(ins)

	fmt.Print("Performing two inserts... ")
	_, err = tr_ins.Run("jeden", 1)
	checkError(err)
	_, err = tr_ins.Run("dwa", 2)
	checkError(err)
	printOK()

	fmt.Print("Commit the transaction... ")
	checkError(tr.Commit())
	printOK()

	fmt.Print("Begining a new transaction... ")
	tr, err = db.Begin()
	checkError(err)
	printOK()

	fmt.Print("Performing one insert... ")
	_, err = tr.Do(ins).Run("trzy", 3)
	checkError(err)
	printOK()

	fmt.Print("Rollback the transaction... ")
	checkError(tr.Rollback())
	printOK()

	fmt.Println("Select from A... ")
	rows, res := checkedResult(sel.Exec())
	name := res.Map("name")
	number := res.Map("number")
	for ii, row := range rows {
		fmt.Printf("%d: %-10s %-8d\n", ii, row[name], row[number])
	}

	fmt.Print("Remove A... ")
	checkedResult(db.Query("drop table A"))
	printOK()

	fmt.Print("Close connection... ")
	checkError(db.Close())
	printOK()
}