上一篇博客里,提到了如何创建数据库连接工具,这一篇中,就来谈谈数据库方法
首先,数据库中需要新建一个表,自己设计内容,然后根据表中的内容,建立一个实体函数,用来创建实体对象,实体函数中要提供与数据库对应的成员函数,建立有参的构造函数,getter和setter方法,tostring方法,然后,新建一个dao层函数,用来写查询方法(正常的情况下,应该是先写接口函数,然后在实现类中写实现方法,在sevelet中调用,然后jsp上显示,但是因为建立的java项目,不是web项目,所以就在dao层中写方法并调用方法测试一下)。dao层中具体内容如下:
package com.yc123.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.yc123.entity.userTable;
import com.yc123.jdbc.DBUtil;
public class UserTableDao {
//查询所有数据列表方法
public List<userTable> queryAll(){
//创建列表 用于存储 对象
List<userTable> list = new ArrayList<userTable>();
//创建对象
userTable ut = null;
//创建数据库连接工具 对象
DBUtil db = new DBUtil();
//连接数据库
Connection conn = db.conn();
//编辑数据库语句,取出所有 userTable 存入字符串中
String sql = "select * from userTable";
//定义预编译
PreparedStatement ps = null;
//定义结果集,用于接收预编译的数据
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery(sql);
//遍历结果集,取出对象,存入集合列表中
while(rs.next()){
ut = new userTable(rs.getString("userName"), rs.getInt("userId"), rs.getString("userAddress"), rs.getInt("userTel"));
list.add(ut);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
//关闭数据库连接
db.closeDB(rs, ps, conn);
}
//返回集合列表
return list;
}
public static void main(String[] args) {
//创建当前类 对象
UserTableDao utd = new UserTableDao();
//创建list集合,接收query方法返回的集合
List<userTable> list = utd.queryAll();
//遍历集合,显示数据库中的结果
for (userTable userTable : list) {
System.out.println(userTable.toString());
}
}
}
输出结果为:
Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
userTable [userName=小白, userId=1001, userAddress=成都, userTel=1234567891]
userTable [userName=小会, userId=1002, userAddress=广州, userTel=1234567891]
userTable [userName=小明, userId=1003, userAddress=北京, userTel=1651546546]
userTable [userName=小芳, userId=1004, userAddress=重庆, userTel=1231564643]
userTable [userName=小南, userId=1005, userAddress=上海, userTel=1215313154]