本次教程是在Maven项目中演示
首先引入mysql
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
编写工具类
public class JdbcUtils {
@Value("${second.url}")
static String url = "jdbc:mysql://localhost:3306/blue?
useUnicode=true&characterEncoding=utf-8&useSSL=false";
@Value("${second.username}")
static String username = "root";
@Value("${second.password}")
static String password = "root";
@Value("${second.driver-class-name}")
static String driverName = "com.mysql.jdbc.Driver";
static Connection conn = null;
static Statement stmt = null;
static ResultSet rs = null;
public static ResultSet connect(String sql) {
try {
// 连接到MySQL数据库
Class.forName(driverName);
conn = DriverManager.getConnection(url, username, password);
// 执行查询操作
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}
catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return rs;
}
public static void close(){
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Value注解的作用是在application.yml配置文件上取数据,如果取不到就使用默认数据
在程序中使用工具类
public void connect() {
String sql = "SELECT id ,`name` ,age FROM student where id = "+1;
try {
ResultSet rs = JdbcUtils.connect(sql);
// 处理查询结果
log.info("sql-->{}",sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
JdbcUtils.close();
}
}
工具类的编写和使用就这样吧