JDBC的泛化设计
时间:2022-04-27
本文章向大家介绍JDBC的泛化设计,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
在mysql数据库中建立如下数据库及表结构作测试使用:
create database market;
use market;
create table client(
id int primary key AUTO_INCREMENT,
num nvarchar(12) unique,
password varchar(20) not null)engine=innoDB default charset=utf8;
insert into client values(1,'root','root');
在eclipse建立一个工程,工程目录结构如下:
1.ConnectionUtil在进行数据库交互的过程中,只使用数据库对象,而不进行具体对象的操作。
在ConnectionUtil中,放置一些数据库的基本对象:
private Connection conn;
private Statement stat;
private PreparedStatement ps;
在ConnectionUtil的构造器中,进行数据库对象的初始化和数据库的连接:
public ConnectionUtil(String url){
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url);
stat=conn.createStatement();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
在ConnectionUtil中,另保存一些数据库操作的基本方法:
1).查找
public ResultSet find(String sql){
try {
return stat.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
2).删除
public int delete(String sql){
try {
return stat.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
3).SQL防注入通过id进行的查找和删除操作
public int executeById(String sql,int id){
try {
ps=conn.prepareStatement(sql);
ps.setInt(1,id);
return ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
4).SQL防注入根据字段定制的更新操作
public int executeUpdate(String sql,String num,String password,int id){
try {
ps=conn.prepareStatement(sql);
ps.setString(1, num);
ps.setString(2, password);
ps.setInt(3,id);
return ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
public int executeUpdate(String sql,int id,String num,String password){
try {
ps=conn.prepareStatement(sql);
ps.setInt(1,id);
ps.setString(2, num);
ps.setString(3, password);
return ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
在ConnectionUtil中的收尾工作:
1).关闭Statement
public void close(Statement stat){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2).关闭Connection
public void close(Connection conn){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.Client类 (JavaBean)在业务处理层保存数据信息
public class Client {
private int id;
private String num;
private String password;
public Client() {
super();
// TODO Auto-generated constructor stub
}
public Client(int id, String name, String password) {
super();
this.id = id;
this.num = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((num == null) ? 0 : num.hashCode());
result = prime * result
+ ((password == null) ? 0 : password.hashCode());
return result;
}
public String toString() {
return "client id=" + id + ", num=" + num + ", password=" + password;
}
}
3.在ClientDao层将数据库对象转换为具体对象,该处为Client类对象
在ClientDao中保存成员工具对象,类初始化的时候实例化该工具对象
private ConnectionUtil util;
public ClientDao(String url) {
super();
util=new ConnectionUtil(url);
}
获取所有的Client对象:
public List<Client> queryClients(){
List<Client> list=new ArrayList<Client>();
ResultSet set=util.find("select * from client");
try {
while(set.next()){
Client temp=new Client(set.getInt(1),set.getString(2),set.getString(3));
list.add(temp);
}
}catch (SQLException e) {
e.printStackTrace();
}
util.close(set);
return list;
}
根据id查找对象:
public Client queryClient(int id){
Client client=null;
ResultSet set=util.preparedFindById("select * from client where id=?", id);
try {
while(set.next())
client=new Client(set.getInt(1),set.getString(2),set.getString(3));
}catch (SQLException e) {
e.printStackTrace();
}
util.close(set);
return client;
}
插入Client对象:
public int insertClient(Client client){
return util.executeUpdate("insert into client values(?,?,?)", client.getId(), client.getNum() , client.getPassword());
}
根据id更新client对象:
public int updateClient(Client client){
return util.executeUpdate("update client set num=?,password=? where id=?", client.getNum(),client.getPassword(),client.getId());
}
根据id删除client对象:
public int deleteById(int id){
return util.executeById("delete from client where id=?", id);
}
删除所有的client对象:
public int deleteClients(){
return util.delete("delete from client");
}
4.最后再写一个测试驱动Tester:
public class Tester {
private static ClientDao dao = new ClientDao(
"jdbc:mysql://localhost:3306/market?user=root&password=" +
"&useUnicode=true&characterEncoding=UTF8");
public static void main(String[] args) {
// test01();
// test02();
// test03();
// test04();
// test05();
// test06();
}
// test:queryClients();
public static void test01(){
List<Client> list = new ArrayList<Client>();
list = dao.queryClients();
System.out.println(list);
}
// test:queryClient(int id);
public static void test02(){
System.out.println(dao.queryClient(1));
}
// test:insertClient(Client client);
public static void test03(){
Client client=new Client(2,"admin","admin");
if(dao.insertClient(client)==1)
System.out.println("Insert successfully!");
else
System.out.println("Insert incorrectly!");
}
// test:updateClient(Client client);
public static void test04(){
Client client=new Client(1,"login","login");
if(dao.updateClient(client)==1)
System.out.println("Update successfully!");
else
System.out.println("Update incorrectly!");
}
// test:deleteById(int id);
public static void test05(){
if(dao.deleteById(2)==1)
System.out.println("Delete successfully by id!");
else
System.out.println("Delete incorrectly by id!");
}
// test:deleteClients();
public static void test06(){
if(dao.deleteClients()==1)
System.out.println("Delete all successfully!");
else
System.out.println("Delete all incorrectly!");
}
}
下面是测试结果:
在jdbc中可以将数据库对象和具体对象的操作绑定在一起,但是每多一个具体对象就需要多一个dao层的转化类。
本文将数据库操作单独封装在一起,每当多一个具体对象时只需要编写实现对具体对象操作的代码就好了。
- Vue 大法好
- Python:ip地址处理模块
- Oracle 12c系列(四)|资源隔离之IO、内存、CPU
- Python:gethostbyname获取本地ip地址
- Oracle 12c系列(五)|PDB Refresh
- hdu 2473 Junk-Mail Filter (并查集之点的删除)
- Python:platform获取操作系统详细信息
- java版本的学生管理系统
- Python:获取目录下指定后缀的文件
- Go语言基于Socket编写服务器端与客户端通信的实例
- Linux强制用户首次登陆修改密码
- crontab执行python脚本提示ImportError解决方法
- Java学习之约瑟夫环的两中处理方法
- Zabbix实现QQ报警配置
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- django实现模型字段动态choice的操作
- 详解ASP.NET Core 处理 404 Not Found
- Python AutoCAD 系统设置的实现方法
- Python如何操作office实现自动化及win32com.client的运用
- android Palette调色板使用详解
- python 穷举指定长度的密码例子
- Android 高仿微信朋友圈拍照上传功能
- android的ListView点击item使item展开的做法的实现代码
- Android NavigationView头部设置监听事件
- android如何取得本地通讯录的头像的原图的实现代码
- 取消Android Studio项目与SVN关联的方法
- Android编程实现获取当前系统语言及地区并更改语言的方法
- Android Studio绑定下拉框数据详解
- python中的socket实现ftp客户端和服务器收发文件及md5加密文件
- Android XRecyclerView实现多条目加载