zoukankan      html  css  js  c++  java
  • Go Mysql使用

    Go Mysql

    @(Golang)

    说明

    1. 安装

    go get github.com/go-sql-driver/mysql 
    go get github.com/jmoiron/sqlx
    

    2. 连接

    database, err := sqlx.Open("mysql", "root:XXXX@tcp(127.0.0.1:3306)/test")
    //database, err := sqlx.Open("数据库类型", "用户名:密码@tcp(地址:端口)/数据库名")
    

    3. 查询

    package main
    
    import (
    	"fmt"
    	_ "github.com/go-sql-driver/mysql"
    	"github.com/jmoiron/sqlx"
    )
    
    //create table person (user_id int not null primary key auto_increment,username varchar(100) not null default '');
    type Person struct {
    	UserId   int    `db:"user_id"`
    	Username string `db:"username"`
    }
    
    func main() {
    
    	db, err := sqlx.Open("mysql", "root:password1@tcp(127.0.0.1:3307)/kutest")
    	if err != nil {
    		fmt.Println("open mysql fail", err)
    		db.Close()
    		return
    	}
    	var person []Person
    	err1 := db.Select(&person, "select user_id,username from person where user_id=?", 2)
    	if err1 != nil {
    		fmt.Println("execute fail", err1)
    		return
    	}
    	fmt.Println("select succ", person)
    }
    

    3. 执行语句

    r, err1 := db.Exec("insert into person set user_id=?, username=? ", 10, "kevinlu")
    

    执行后立刻commit

    4. 事务

    conn, err := db.Begin()
    conn.Exec("insert into person set user_id=?, username=? ", 20, "kevinlu20")
    conn.Exec("insert into person set user_id=?, username=? ", 21, "kevinlu21")
    conn.Commit()
    //conn.Rollback() //回滚
    
  • 相关阅读:
    CF899A Splitting in Teams
    CF898A Rounding
    CF914A Perfect Squares
    CF864A Fair Game
    CF909A Generate Login
    关于C++的一些函数的使用方法
    又是一个二模02,不过day2
    2模02day1题解
    二模Day2题解
    KMP算法心得
  • 原文地址:https://www.cnblogs.com/Xjng/p/14814408.html
Copyright © 2011-2022 走看看