创建数据表过程省略 (这里我随便拿以前项目一个表来用)!!!
版本:Java8和mysql8
实体类:
public class Classes { private Integer classId; private String className; public Classes(Integer classId, String className) { this.classId = classId; this.className = className; } public Integer getClassId() { return classId; } public void setClassId(Integer classId) { this.classId = classId; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } @Override public String toString() { return "Classes{" + "classId=" + classId + ", className='" + className + ''' + '}'; } }
实现代码如下:
import java.sql.*; import java.util.ArrayList; import java.util.List; public class Datebase { public void connectDate() { String url = "jdbc:mysql://localhost:3306/students?useSSL=true&useUnicode=true&characterEncoding=UTF-8"; String username = "root"; String password = "root"; try { //加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //建立连接 Connection con = DriverManager.getConnection(url,username,password); //编写sql语句 String sql1 = "select * from class"; //执行sql PreparedStatement statement = con.prepareStatement(sql1); //结果集接收从数据库查到的数据 ResultSet resultSet = statement.executeQuery(); //初始化一个List集合,将resultSet中的记录一条条放进List集合中 Listlist = new ArrayList<>(); while (resultSet.next()){ list.add(new Classes(resultSet.getInt("class_id"),resultSet.getString("class_name"))); } for (Classes classes : list){ System.out.println(classes); } //关闭连接 con.close(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } }
测试:
public class Test { public static void main(String[] args) { Datebase datebase = new Datebase(); datebase.connectDate(); } }
运行结果:
这是Java实现 *** 作数据库比较基础的方式,在后面框架中 (例如:Mybatis),会变的很简单,
后面我也会更新利用框架 *** 作Mysql数据库的实现。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)