当前位置:网站首页>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);
}
}
边栏推荐
- Event log keyword: eventlogtags logtags
- 第十六届东北地区大学生程序设计竞赛(热身赛)B-String Value(字符串dp)
- Master shell, one article is enough!
- gis利器之Gdal(三)gdb数据读取
- 物联网开源开发平台 Shifu 开放内测!第一版技术文档发布
- Go 分组 & 排序
- How to conduct exploratory data analysis
- What do Niu B programmers pay attention to when "creating an index"?
- 面对新的挑战,成为更好的自己--进击的技术er
- MCS:离散随机变量——Bernoulli分布
猜你喜欢

JVM原理之完整的一次GC流程

Drag and drop frame

Arduino flame sensor (with code)

Raspberry pie network remote access

I have been engaged in software testing for 5 years and have changed jobs for 3 times. I have understood the field of software testing

Missing essential plugin

Introduction to unityshader -- rendering optimization technology in unity (IV)

What do Niu B programmers pay attention to when "creating an index"?
![[microservices | Nacos] list of issues related to the Nacos version](/img/13/d25cbe38d1712f7166f7b5eb27942c.png)
[microservices | Nacos] list of issues related to the Nacos version

Calculate Euclidean distance and cosine similarity
随机推荐
[laravel series 7.8] broadcasting system
Fund performance evaluation
Penetration test basis | attached test points and test scenarios
Zygote process
第九章 APP项目测试(1)
Rtklib new version 2.4.3 B34 test comparison
onnxoptimizer、onnxsim使用记录
Arduino flame sensor (with code)
Strong push, quick start to software testing
C language stack implementation
PHP move_ uploaded_ File failed to upload mobile pictures
[microservices | Nacos] Nacos realizes data isolation of multi environment and multi tenant
How can functional testers spend one month to become advanced automation software test engineers
Hcip reissue experiment
What is the average annual salary of an outsourced tester who has worked for 5-8 years?
Qt QWidget嵌套相对位置获取 (qt 画线 嵌套)
Visual display of TEQC quality analysis results using teqcplot
MCS:连续随机变量——Chi-Square分布
Drag and drop拖放框架
Hard core, become a high-quality tester: learn to communicate with products