前言:
使用中,通过原生JDBC 进行数据库的连接及基础操作
基础步骤:
1、加载驱动
2、创建连接
3、预编译sql
4、执行接收结果
5、结果处理转化
相关包:
驱动包 mysql-connector-java-8.0.28.jar
实体补充包 lombok-1.18.10.jar
实体类:(承接结果转化)
import lombok.Data;
/**
* @author:
* @date:2023/5/24
* @description:
*/
@Data
public class User {
//用户id
private int id;
//用户名
private String username;
//用户密码
private String password;
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
}
主方法:
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author:
* @date:2023/5/24
* @description:
*/
public class Test2copy {
public List<User> resultSetToList(ResultSet ret) {
User user=null;
List list = new ArrayList();
try {
while (ret.next()){
Integer id=ret.getInt("id");
String username=ret.getString("username");
String password=ret.getString("password");
user =new User(id,username,password);
list.add(user);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return list;
}
//关闭资源
public void closeResouce(Connection conn,ResultSet rs,PreparedStatement pstmt){
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void main(String[] args) {
Connection com = null;
PreparedStatement pst = null;
ResultSet ret = null;
Test2copy tes = new Test2copy();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//dburl jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
// root -u root -p
com = DriverManager.getConnection("dburl", "root", "root");
pst = com.prepareStatement("select * from User");
ret = pst.executeQuery();
List<User> users = tes.resultSetToList(ret);
System.out.print("------------+++"+users.size());
}catch (Exception e){
}finally{
tes.closeResouce(com,ret,pst);
}
}
}