环境:
- JDK: 17
- mysql: 5.7
和数据库打交道,在项目开发中是在所难免的。今天简单学习下在 java 中 原生操作 MySQL,demo通过 maven做依赖管理。
依赖
在新建 maven 项目后,加入依赖:
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.1.0</version>
</dependency>
</dependencies>
添加依赖时要注意,我们上面的依赖是新的包名。
配置文件
在我们的配置文件中声明需要注入的配置项:
url=jdbc:mysql://{ip}:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=123456
构建工具类
我们在工具类中,主要声明 创建连接和关闭连接 两项功能:
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class Util {
public static Connection getConn() {
Connection conn = null;
try {
Properties properties = new Properties();
try {
InputStream in = Util.class.getClassLoader().getResourceAsStream("app.properties");
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
System.out.println("未找到配置文件");
}
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动类找不到");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
}
return conn;
}
public static void close(Connection conn, Statement stm, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
测试查询
在有了工具类后,就通过简单的查询操作:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class testSqlSelect {
public static void main(String[] args) {
Connection conn = null;
Statement stm = null;
ResultSet rs = null;
try {
conn = Util.getConn();
String sql = "SELECT * FROM user";
stm = conn.createStatement();
rs = stm.executeQuery(sql);
System.out.println("查询结果:");
while (rs.next()) {
String name = rs.getString("name");
System.out.println("Name:" + name);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
Util.close(conn, stm, rs);
}
}
}
测试结果
查询结果:
Name:Jack
Name:Tom
mysql表内容
参考:
标签:java,17,5.7,rs,mysql,catch,import,conn From: https://www.cnblogs.com/davis12/p/17926711.html