JDBC 连接、增加、查询
需要创建一个类获取数据库连接
连接类的内容:
创建一个字符串常量存放数据库的信息
private static final String CONN_STR="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
创建一个字符串常量保存数据库用户名
private static final String USER="work";
创建一个字符串常量保存数据库用户密码
private static final String PWD="work";
获取数据库连接方法
//获取数据库连接
public static Connection getConn() {
Connection conn =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //查找库里是否拥有
conn= DriverManager.getConnection(CONN_STR,USER,PWD); //数据库位置,用户名,密码
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;//返回数据库信息
}
//关闭数据库流
public static void releaseRec(Connection conn,PreparedStatement pstmt,ResultSet rset) {
try {
if(rset!=null)rset.close();
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Dao层实现类
//实现添加功能
private static final String SQL_ADD="insert tbl_student(stu_name,stu_height) values(?,?)";//设置添加SQL语句
private static final String SQL_LOAD_ALL="select * from tbl_student";//设置查询SQL语句
Connection conn = DBUtils.getConn();//获取数据库连接
PreparedStatement pstmt= null; //定义存放数据变量
pstmt=conn.prepareStatement(SQL_ADD); //存放SQL操作语句
pstmt.setString(1, student.getStuName());//存放第一个问号所对应的数据
pstmt.setDouble(2, student.getStuHeight());//存放第二个问号所对应的数据
pstmt.executeUpdate();//通过该方法把数据存入数据库中
//实现查询功能
Connection conn= DBUtils.getConn();//获取数据库连接
PreparedStatement pstmt=null;//存放数据
ResultSet rest = null;//接受查询返回的数据
List<Student> stuList = new ArrayList<>();//接受返回的多条数据
pstmt= conn.prepareStatement(SQL_LOAD_ALL);//存放SQL操作语句
rest=pstmt.executeQuery();//返回的数据
while(rest.next()) {//rest.next 检测指向的位置还是否拥有记录
Student stu= new Student();
stu.setStuNo(rest.getInt("stu_no")); //取出数据以对象的形式保存
//什么类型的数据就是get什么类型的数据
stu.setStuName(rest.getString("stu_name"));
stu.setStuHeight(rest.getDouble("stu_height"));
stuList.add(stu);//向数组中保存对象
}