封装JDBC
为了更加方便的对数据库进行增删改查,就需要将连接数据库的方法进行封装,这样我们开发的时候便能更加方便的进行开发。做到写更少的代码,做更多的事儿。下面呢我将展示使用封装后的工具对数据库进行操作
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
/**
* @author Rhine_He
* @date 2020-06-24-15:23
* @fuction JDBC封装
**/
public class DBUtilUseProperties {
private static final Properties pro = new Properties();
static Connection connection =null;
static PreparedStatement preparedStatement =null;
static ResultSet resultSet=null;
static {
InputStream is = DBUtilUseProperties.class.getResourceAsStream("db.propertise");
try {
pro.load(is);
Class.forName(pro.getProperty("driver"));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
connection = DriverManager.getConnection(pro.getProperty("url"),
pro.getProperty("user"),pro.getProperty("password"));
return connection;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
测试
import bean.User;
import jdbcPool.JDBCPool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;
/**
* @author Rhine_He
* @date 2020-06-24-15:37
**/
public class JDBCDemoUseUtil2 {
public static void main(String[] args) throws Exception {
/*
*使用垃圾的封装JDBC操作:
*/
/* Connection connection = DBUtilUseProperties.getConnection();
*//* //该方法比较慢,还存在SQL注入的危险
Statement statement = connection.createStatement();
int result = statement.executeUpdate("insert into user(userid,username,sex)values(5,'孙七','男')");*//*
//以下方法有效避免SQL注入的风险,先编译,后运行
String sql="insert into user(userid,username,sex)values(2,'李四','男')";
PreparedStatement statement = connection.prepareStatement(sql);
int result =statement.executeUpdate();
if(result != -1){
System.out.println("注册成功!");
}else {
System.out.println("注册失败!");
}
DBUtilUseProperties.closeAll(connection,statement,null);*/
/*
*使用比较好的封装JDBC,你就只需要使用封装好的类调用方法,传递SQL和参数们,
* 如果是查询还需要传递返回的对象的类例如学生对象:(Student.class)前提,自己写有Student实体类
*/
//修改数据:该方法可以进行数据库数据的修改和删除
DBUtilUseProperties.update("delete from user where userid>?",5);//删除
DBUtilUseProperties.update("update user set username=? where userid=? ","张飒",2);//修改
//查询数据
User user = DBUtilUseProperties.queryOne("select *from user where userid=?",User.class,4);//查询一条数据
System.out.println(user);
//查询多条数据
List<User> users = DBUtilUseProperties.queryList("select *from user", User.class, null);
for (Object object : users) {
System.out.println(object);
}
}
}