package main
import(
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
)
var (
Id string
Name string
)
func main(){
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/go?charset=utf8")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
update(db)
sqlselect(db)
insert(db)
fmt.Println("插入后")
sqlselect(db)
delete(db);
fmt.Println("删除后")
sqlselect(db)
}
// 查询 数据
func sqlselect(db *sql.DB) {
rows,err := db.Query("select * from test")
if err != nil {
fmt.Println("数据库查询出错执行出错")
}
for rows.Next(){
//按表名的顺序读取参数
err := rows.Scan(&Name,&Id)
if err != nil {
log.Fatal(err)
}
fmt.Println(Name, Id)
}
rows.Close()
}
//更新
func update(db *sql.DB) {
result,err:=db.Exec("update test set Id = 1123 WHERE test.Name=?","a")
if err != nil {
fmt.Println("数据库执行更新出错")
}
changelow,err:=result.RowsAffected()
if err != nil {
}
fmt.Println("共计",changelow,"行受到影响")
}
//INSERT INTO `go`.`test` (`Id`, `Name`) VALUES ('4', 'd');
//插入
func insert(db *sql.DB){
result,err:=db.Exec("INSERT test (Id, Name) VALUES (?,?)","5","e")
if err != nil {
fmt.Println("数据库执行插入出错",err)
return
}
changelow,err:=result.RowsAffected()
if err != nil {
}
fmt.Println("共计",changelow,"行受到影响")
}
//DELETE FROM `go`.`test` WHERE `Id` = '5';
//删除第5条数据
func delete(db *sql.DB){
result,err:=db.Exec("DELETE FROM test WHERE `Id` = ?",5)
if err != nil {
fmt.Println("数据库执行删除出错",err)
return
}
changelow,err := result.RowsAffected()
if err != nil {
}
fmt.Println("共计",changelow,"行受到影响")
}
贴出 创建sql的数据
CREATE TABLE `test` (
`Id` int(11) NOT NULL,
`Name` char(200) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
msq的 url 规则
user@unix(/path/to/socket)/dbname
root:pw@unix(/tmp/mysql.sock)/myDatabase?loc=Local
user:password@tcp(localhost:5555)/dbname?tls=skip-verify&autocommit=true
参考链接点击打开链接