当前位置:网站首页>JDBC introductory learning (II) encapsulation tool class
JDBC introductory learning (II) encapsulation tool class
2022-06-23 05:24:00 【The silent Lord returns to the sand】
- Encapsulation of tool class ( a key )
// problem : Every time CRUD operation , You have to write a set JDBC, tedious
// Solution : Will repeat the operation , Extract into tool classes to encapsulate
//1. You only need to load the driver once --- Put it in a static code block
// problem 2: Drive the database directly in the tool class , Database name , user name , The code is dead , Inconvenient for subsequent changes --- Hard encoding
// Solution : Need to change to soft coding form , Make the program more flexible , More maintainable
public class LoginTest {
public static void main(String[] args) {
System.out.println(" Please enter a user name ");
Scanner sc = new Scanner(System.in);
String username = sc.nextLine(); // Get a line of content
System.out.println(" Please input a password ");
String password = sc.nextLine();
if(login2(username,password)){
// Login function
System.out.println(" Login successful ~!");
}else{
System.out.println(" Login failed ~!");
}
}
private static boolean login2(String username, String password) {
Connection conn = null;
PreparedStatement prst = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("select count(*) from user where username=? and password=?");
// Parameters 1: Corresponds to the first placeholder ? Subscript from 1 Start
prst.setString(1,username);
prst.setString(2,password);
// Get the result set
//sql Injection potential
rs = prst.executeQuery();
if(rs.next()){
int result = rs.getInt(1); // The aggregate function has only one field
return result>0; //result Not less than 0, Then return to true
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(rs,prst,conn);
}
return false;
}
private static boolean login(String username, String password) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
st = conn.createStatement();
// Get the result set
//sql Injection potential
String sql = "select count(*) from user where username='"+username+"' and password='"+password+"'";
rs = st.executeQuery(sql);
if(rs.next()){
int result = rs.getInt(1); // The aggregate function has only one field
return result>0; //result Not less than 0, Then return to true
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(rs,st,conn);
}
return false;
}
}
public class DBUtils {
private static Properties p = new Properties();
// Static code block : Load only once
static{
// Reflection object calls getResourceAsStream
// from src Get... From the directory db.properties Resources for
try {
InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
p.load(is);
Class.forName(p.getProperty("driver"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password"));
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void closeAll(AutoCloseable...cs){
for(AutoCloseable c : cs){
if(c!=null){
try {
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Extraction of configuration files
Create your own in the root directory db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mydb1
username=root
password=123
- ORM ( a key )
Object relation mapping : object - Entity class ( Don't put main Class of method ), Relationship - Data sheet , Data conversion between the two
In short , Is to take data from the data table , Stored in entity classes
// Case study : Get the information of the position table , Stored in entity classes
// Create an entity class corresponding to the relation table : Object properties = Table field
// The scattered field values in the data table , Encapsulated into entity classes , Convenient operation
@Data // Generate set/get And toString
@NoArgsConstructor // Generate a nonparametric construct
@AllArgsConstructor // Generate all parameter constructs
class Jobs{
private String job_id;
private String job_title;
private String min_salary;
private String max_salary;
}
public class Test1 {
public static void main(String[] args) throws SQLException {
Connection conn = DBUtils.getConnection();
PreparedStatement prst = conn.prepareStatement("select * from t_jobs");
ResultSet rs = prst.executeQuery();
while(rs.next()){
String job_id = rs.getString("job_id");
String job_title = rs.getString("job_title");
String min_salary = rs.getString("min_salary");
String max_salary = rs.getString("max_salary");
Jobs jobs = new Jobs(job_id,job_title,min_salary,max_salary);
System.out.println(jobs); // Object relation mapping : Save the table field contents in the entity attribute
}
DBUtils.closeAll(rs,prst,conn);
}
}
- Dao Extraction of layers ( a key )
Dao layer : Data access layer , Used to do things that interact with the database
If not dao Layer extraction , For example, the login function , All the code is put into the test class , Make the test class code particularly bloated
Code separation design after extraction :
main Method to perform business logic operations ; dao Layer only jdbc operation
Case study : Person The operation of adding, deleting, modifying and querying data table
Create data table
> - Create a table Person, There are the following :
> - id:int, Primary key , Automatic growth
> - name:varchar(20) Non empty
> - age:int Non empty
> - bornDate:Date
> - email: character string
> - address: character string
// In the test class , Do business logic operations
// Operation steps :
//1. Create data table
//2. New entity class
//3. Write a tool class
//4. take jdbc Abstract to dao layer
//5. Write business logic in the test class
//------------ Create entity class ------------
// The attributes in the entity class should be consistent with the table fields --ORM
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private int id;
private String name;
private int age;
private Date bornDate;
private String email;
private String address;
}
//------------ Create test class ------------
public class Test1 {
public static void main(String[] args) {
System.out.println(" Please input what you want to do :1. add to 2. modify 3 Delete 4 Check all 5. according to id check ");
PersonDaoImpl personDao = new PersonDaoImpl();
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
switch (num){
case 1: // Add a transfer object , Generally, the primary key grows automatically ,id Never mind
int result = personDao.insert(new Person(0,"ls",20,new Date(),"[email protected]"," hubei "));
System.out.println(" Insert :"+result);
break;
case 2: // Modify the transfer object , There must be a modified primary key id, To modify the
result = personDao.update(new Person(2,"ww",44,new Date(),"[email protected]"," jiangxi "));
System.out.println(" modify :"+result);
break;
case 3:
result = personDao.delete(1); // Delete id
System.out.println(" Delete :"+result);
break;
case 4: // Query all , return List aggregate
List<Person> list = personDao.selectAll();
System.out.println(" Check all :"+list);
break;
case 5: // Query individual , Often based on id check , Return entity object
Person person = personDao.selectById(2);
System.out.println(" Query object :"+person);
break;
default:
System.out.println(" Your input is wrong ~");
break;
}
}
}
//------------ establish dao Layer operation ------------
//dao layer -- Data access layer ( Used to do jdbc operation )
public class PersonDaoImpl {
public int insert(Person person) {
Connection conn = null;
PreparedStatement prst = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("insert into person(name,age,bornDate,email,address) values(?,?,?,?,?)");
prst.setString(1,person.getName());
prst.setInt(2,person.getAge());
//sql Under bag new Date( Parameters ) Sure long Millisecond value parameter of type
prst.setDate(3,new Date(person.getBornDate().getTime()));
prst.setString(4,person.getEmail());
prst.setString(5,person.getAddress());
return prst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(prst,conn);
}
return 0;
}
public int update(Person person) {
Connection conn = null;
PreparedStatement prst = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("update person set name=?,age=? where id=?");
prst.setString(1,person.getName());
prst.setInt(2,person.getAge());
prst.setInt(3,person.getId());
return prst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(prst,conn);
}
return 0;
}
public int delete(int id) {
Connection conn = null;
PreparedStatement prst = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("delete from person where id=?");
prst.setInt(1,id);
return prst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(prst,conn);
}
return 0;
}
public Person selectById(int id) {
Connection conn = null;
PreparedStatement prst = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("select * from person where id=?");
prst.setInt(1,id);
rs = prst.executeQuery();
if(rs.next()){
String name = rs.getString("name");
int age = rs.getInt("age");
Date bornDate = rs.getDate("bornDate");
String email = rs.getString("email");
String address = rs.getString("address");
return new Person(id,name,age,bornDate,email,address);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.closeAll(rs,prst,conn);
}
return null;
}
public List<Person> selectAll() {
Connection conn = null;
PreparedStatement prst = null;
ResultSet rs = null;
List<Person> list = new ArrayList<>();
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("select * from person");
rs = prst.executeQuery();
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
Date bornDate = rs.getDate("bornDate");
String email = rs.getString("email");
String address = rs.getString("address");
list.add(new Person(id,name,age,bornDate,email,address));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.closeAll(rs,prst,conn);
}
return list;
}
}
3.1 DateUtils
Date tool class
In the project , Date classes may need to be converted to each other
for example :String turn Date,Date turn String,Utils Of Date turn SQL Of Date
// Conversion method of date class :
public class DateUtils {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public static Date utilToSQL(java.util.Date date){
return new Date(date.getTime());
}
public static String utilToString(java.util.Date date){
return sdf.format(date);
}
public static java.util.Date stringToUtil(String strDate){
try {
return sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
4.Service The business layer ( a key )
Used for business logic analysis , A business function can contain one or more dao operation
for example : Transfer business –> Detailed analysis
A business –> Multiple dao, Determine the sender's account , Correctness of the recipient's account , Whether the money is enough
Finally, the transfer function can be performed – Add money to an account , Another user reduces money
The above are all business analysis areas

Case study : Function decomposition of transfer business
- Create a table account, There are the following :
- id:int, Primary key , Automatic growth
- cart :varchar(40) Non empty
- password : character string
- money :double(8,2)
// Operation steps :
//1. Create data table , Insert two pieces of data
//2. Create entity class Account
//3. establish DBUtils Database tool class
//4. Create a business layer , Conduct transfer business analysis
//5. Specifically, it interacts with the database , hand dao layer
//6. Test in a test class
//--------- Create entity class ---------
// Create entity class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
private int id;
private String card;
private String password;
private double money;
}
//---------- Business logic analysis -----------
// Transfer business
public class AccountServiceImpl {
private AccountDaoImpl accountDao = new AccountDaoImpl();
// Business functions of transfer
public String tansfer(String sendCard,double money,String recvCard,String password){
//1. According to the sender's account , Get objects , If not, an exception will be reported
Account sendAccount = accountDao.selectCard(sendCard);
if(sendAccount==null){
throw new RuntimeException(" Sender account does not exist !");
}
//2. If there is , Got the object , See if the password is correct , Is the amount enough
if(!password.equals(sendAccount.getPassword())){
throw new RuntimeException(" Wrong password ");
}
if(sendAccount.getMoney()<money){
throw new RuntimeException(" Lack of balance ");
}
//3. Determine whether the receiver's account exists , If it doesn't exist , Abnormal Report
Account recvAccount = accountDao.selectCard(recvCard);
if(recvAccount==null){
throw new RuntimeException(" The recipient account does not exist ");
}
//4. Transfer money --> The sender reduces money (update), The receiver adds money (update)
sendAccount.setMoney(sendAccount.getMoney()-money);
int result = accountDao.update(sendAccount);
System.out.println(" Sender modification :"+result);
recvAccount.setMoney(recvAccount.getMoney()+money);
result = accountDao.update(recvAccount);
System.out.println(" Sender modification :"+result);
return " Transfer succeeded ~~!";
}
}
//---------- Data access layer ----------
public class AccountDaoImpl {
public Account selectCard(String card) {
Connection conn = null;
PreparedStatement prst = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("select * from account where card=?");
prst.setString(1,card);
rs = prst.executeQuery();
if(rs.next()){
int id = rs.getInt("id");
String password = rs.getString("password");
double money = rs.getDouble("money");
return new Account(id,card,password,money);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.closeAll(rs,prst,conn);
}
return null;
}
public int update(Account recvAccount) {
Connection conn = null;
PreparedStatement prst = null;
try {
conn = DBUtils.getConnection();
prst = conn.prepareStatement("update account set money=? where id=?");
prst.setDouble(1,recvAccount.getMoney());
prst.setInt(2,recvAccount.getId());
return prst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.closeAll(prst,conn);
}
return 0;
}
}
//------------- Test class -------------
public class Test1 {
public static void main(String[] args) {
AccountServiceImpl accountService = new AccountServiceImpl();
String res = accountService.tansfer("10010",1000,"10086","123");
System.out.println(res);
}
}
边栏推荐
- Snippet Manager snippetslab
- C'est dur de trouver un emploi? Ali des trois côtés, heureusement qu'il s'est bien préparé et qu'il a pris un produit.
- Baidu PaddlePaddle's "universal gravitation" first stop in 2022 landed in Suzhou, comprehensively launching the SME empowerment plan
- [laravel series 7.8] broadcasting system
- (IntelliJ) plug in background image plus
- Economic development is driven by new technology
- Three methods of GNSS velocity calculation
- onnxoptimizer、onnxsim使用记录
- 关于DOS/DDOS攻击和防御
- ES6的Array.from方法创建长度为N的undefined数组
猜你喜欢

Drag and drop frame

Missing essential plugin

LeetCode 797:所有可能的路径

ES6的Array.from方法创建长度为N的undefined数组

【微服务|Nacos】Nacos实现多环境和多租户的数据隔离

Memory model of JVM principle

Three methods of GNSS velocity calculation
![[microservices | Nacos] Nacos realizes data isolation of multi environment and multi tenant](/img/dc/f00a780e96032c0b7d9b6d7c2267d1.png)
[microservices | Nacos] Nacos realizes data isolation of multi environment and multi tenant

网上有真实的兼职吗?大学生怎么找暑期兼职?

stm32时钟树错误配置导致 开机进入硬中断
随机推荐
Laravel8 implementation of picture verification code
戏问花门酒家翁
104. 简易聊天室7:使用 Socket 传递对象
JVM原理之完整的一次GC流程
MCS:连续随机变量——Student’s t分布
小时候 觉得爸爸就是天 无所不能~
When SBAS encounters rtklib
Three methods of GNSS velocity calculation
1010 Radix
面对新的挑战,成为更好的自己--进击的技术er
Seata四大模式之XA模式详解及代码实现
markdown给图片加背景色
Jetpack Compose 从开门到入门之 MenuBar桌面菜单(Desktop Menu)
TIOBE 编程语言排行榜是编程语言流行趋势的一个指标
网上有真实的兼职吗?大学生怎么找暑期兼职?
投资风险管理
关于信息泄露和防御
VMware network connection error unit network service not found
bat中获取bat命令结果
Get bat command results in bat