下面由golang教程栏目给大家介绍go使用mysql测试,希望对需要的朋友有所帮助!
添加测试代码如下
package main import ( "github.com/jmoiron/sqlx" _ "github.com/go-sql-driver/mysql" "fmt" ) func main() { Db,err:=sqlx.Open("mysql","root:123456@tcp(127.0.0.1:3306)/ghnv2_test") if err != nil{ fmt.Println("connect to mysql failed,",err) return } defer Db.Close() fmt.Println("connect to mysql success") //执行sql语句,切记这里的占位符是? result,err := Db.Exec("INSERT INTO sysuser_tag(tag_name,shop_id,user_id)VALUES (?,?,?)","运动",12,24) if err != nil{ fmt.Println("insert failed,",err) } // 通过LastInsertId可以获取插入数据的id tagId,err:= result.LastInsertId() // 通过RowsAffected可以获取受影响的行数 rowCount,err:=result.RowsAffected() fmt.Println("tag_id:",tagId) fmt.Println("rowCount:",rowCount) }
需要安装MySQL包
执行
查询select如下
package main import ( "github.com/jmoiron/sqlx" _ "github.com/go-sql-driver/mysql" "fmt" ) func main() { Db,err:=sqlx.Open("mysql","root:123456@tcp(127.0.0.1:3306)/ghnv2_test") if err != nil{ fmt.Println("connect to mysql failed,",err) return } defer Db.Close() fmt.Println("connect to mysql success") //执行查询操作 rows,err := Db.Query("SELECT tag_name FROM sysuser_tag WHERE tag_id>=7") if err != nil{ fmt.Println("select db failed,err:",err) return } // 这里获取的rows是从数据库查的满足tag_id>=5的所有行的tag_name信息,rows.Next(),用于循环获取所有 for rows.Next(){ var s string err = rows.Scan(&s) if err != nil{ fmt.Println(err) return } fmt.Println(s) } rows.Close() }
结果如下
测试数据库如下
更多golang相关技术文章,请访问go语言栏目!
以上是关于go使用mysql测试的详细内容。更多信息请关注PHP中文网其他相关文章!