# 2. 访问 MySQL
# 2.1 Java —— JDBC
public class JavaVisitMySQL {
public static final String URL = "jdbc:mysql://localhost:3306/database";
public static final String USERNAME = "xxxx";
public static final String PASSWORD = "xxxx";
public static void main(String[] args) throws Exception {
//1. 加载驱动程序
Class.forName("com.mysql.jdbc.cj.Driver");
//2. 获得数据库连接
Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
//3. 操作数据库,实现增删改查
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT user_name, user_age FROM tbl_user");
// 如果有数据,rs.next() 返回 true
while(rs.next()){
System.out.println(rs.getString("user_name")+" 年龄:"+rs.getInt("user_age"));
}
}
}
# 2.2 Golang —— go-sql-driver
下载依赖
- go get -u github.com/go-sql-driver/mysql
package main
import (
"database/sql"
"fmt"
"strings"
// 需要引入
_ "github.com/go-sql-driver/mysql"
)
// 数据库配置
const (
MYSQL_USERNAME = "root"
MYSQL_PASSWORD = "123456"
MYSQL_HOSTNAME = "localhost"
MYSQL_PORT = "3306"
MYSQL_DB_NAEM = "myblog"
)
// 数据库连接池
var dbPool *sql.DB
func main() {
// 连接数据库:username:password@tcp(hostname:port)/dbName?charset=utf8
dbPath := strings.Join([]string{MYSQL_USERNAME,":",MYSQL_PASSWORD,"@tcp(",MYSQL_HOSTNAME,":",MYSQL_PORT,")/",MYSQL_DB_NAEM,"?charset=utf8"},"")
// 打开数据库
dbPool, err := sql.Open("mysql", dbPath)
if err != nil {
fmt.Println("open mysql failed, err:", err.Error())
return
}
// 关闭连接
defer dbPool.Close()
// 验证连接
if err = dbPool.Ping(); err != nil {
fmt.Println("ping mysql failed, err:", err.Error())
return
}
fmt.Println("ping mysql success")
// 读取数据
sql := "select * from blogs;"
result, err := dbPool.Query(sql)
if err != nil {
fmt.Println("query sql failed, err:", err.Error())
return
}
// 循环读取结果
row := &struct {
Id int
Title string
Content string
Author string
}{}
for result.Next() {
err = result.Scan(&row.Id, &row.Title, &row.Content, &row.Author)
if err != nil {
fmt.Println("scan data failed, err:", err.Error())
return
}
fmt.Println("row:", row)
}
}