JDBC的优化使用及类的封装
昨天的实习中,使用了JDBC实现了对MySQL数据库的连接,同时利用SQL语句和Java语言对数据库进行了查询,增添,删除以及更新操作。今天,可以把这几个操作写在同一个main函数中,同时实现对用户信息的封装。
将用户信息单独封装为一个UserInfo类
可以将用户信息单独封装为一个类,在初始化数据库操作时便将从数据库中读出的数据保存在用户信息类的对象中,通过定义私有变量及构造函数来实现对用户信息的封装,
在用户信息类中定义私有变量后,右键-Generate,点击Getter and Setter来快速完成set和get函数的完成;通过点击toString()来生成一个将保存自数据库的信息转换成具有可读性的信息;通过自定义构造函数还实现最私有变量的传参工作,具体代码如下:
public class UserInfo {
private int Uno;
private String Uname;
private String Upwd;
public UserInfo(String uname, String upwd) {
Uname = uname;
Upwd = upwd;
}
@Override
public String toString() {
return "UserInfo{" +
"Uno=" + Uno +
", Uname='" + Uname + '\'' +
", Upwd='" + Upwd + '\'' +
'}';
}
public int getUno() {
return Uno;
}
public void setUno(int uno) {
Uno = uno;
}
public String getUname() {
return Uname;
}
public void setUname(String uname) {
Uname = uname;
}
public String getUpwd() {
return Upwd;
}
public void setUpwd(String upwd) {
Upwd = upwd;
}
}
修改查询操作
同时改写查询操作的函数。因为每次执行result.next()函数都会生成一个用户信息类的对象,故新建一个List类的对象,将每次读出的用户信息保存到Array数组中。
public List<UserInfo> findUsers() {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultset = null;
List<UserInfo> userInfos = new ArrayList<>();
try {
connection = DBUtil.getConn();
String querySql = "select * from userinfo";
statement = connection.prepareStatement(querySql);
resultset = statement.executeQuery();
while (resultset.next()) {
int Uno = resultset.getInt(1);
String Uname = resultset.getString(2);
String Upwd = resultset.getString(3);
UserInfo userInfo = new UserInfo(Uname, Upwd);
userInfo.setUno(Uno);
userInfos.add(userInfo);
}
System.out.println(userInfos);
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(resultset, statement, connection);
}
return userInfos;
}
修改添加操作并在主函数实现
将添加信息的方式修改为先将欲添加的信息添加到用户信息类的对象中,然后用对象中使用getXXX函数读取用户信息,再执行SQL语句将用户信息添加到数据库表中。
public void addUser(UserInfo userInfo) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = DBUtil.getConn();
String addSql = "insert into userinfo (Uno,Uname,Upwd) values (?,?,?)";
statement = connection.prepareStatement(addSql);
statement.setInt(1, userInfo.getUno());
statement.setString(2, userInfo.getUname());
statement.setString(3, userInfo.getUpwd());
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(null, statement, connection);
}
}
将主函数修改:
public static void main(String[] args) {
UserInfoDao test =new UserInfoDao();
List<UserInfo> users = test.findUsers();
test.addUser(new UserInfo("Frank","123456"));
}
实现效果如下:
至此,完成了对用户信息类的封装。