rowquery start

main
Your Name 2024-07-18 21:48:41 +08:00
parent 8af13f9163
commit 6f19983df9
3 changed files with 78 additions and 0 deletions

12
.idea/dataSources.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="wangaodev" uuid="6209a676-34ef-4e7b-8136-12211d26f14c">
<driver-ref>mysql.8</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>com.mysql.cj.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://43.143.245.135:3306/wangaodev</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

6
.idea/sqldialects.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/mysql/mysql_rowquery.go" dialect="GenericSQL" />
</component>
</project>

60
mysql/mysql_rowquery.go Normal file
View File

@ -0,0 +1,60 @@
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql" //自动执行init()
"log"
)
var db *sql.DB //是一个数据库连接池对象
func initDb() (err error) {
//数据库信息
dsn := "root:123456@tcp(43.143.245.135:3306)/wangaodev"
//连接数据库
db, err = sql.Open("mysql", dsn) //不会校验用户名和密码是否正确
if err != nil {
//dsn 格式不正确会报错
return err
}
//校验用户名和密码是否正确
//尝试连接数据库
err = db.Ping()
if err != nil {
return err
}
log.Printf("connect %s success.\n", dsn)
//设置最大连接数
db.SetMaxOpenConns(10)
//设置最大空闲连接数
db.SetMaxIdleConns(5)
return nil
}
// 表结构对象
type user struct {
id int
name string
age int
}
// 查询单行数据
func queryRow(id int) {
var u user
//查询单行记录的sql语句
sqlstr := "select id, name, age from user where id=?"
//执行并且拿到结果
db.QueryRow(sqlstr, id).Scan(&u.id, &u.name, &u.age) //从链接池中拿一个连接出来去数据库查询单条记录,scan方法自动释放连接也就是必须调用scan方法
fmt.Printf("user:%#v\n", u)
}
// go链接mysql示例
func main() {
err := initDb()
if err != nil {
log.Fatalf("init DB failed:%v", err)
}
log.Println("init DB success.")
queryRow(2)
}