当前位置:网站首页>JDBC exercise - query data encapsulated into object return & simple login demo
JDBC exercise - query data encapsulated into object return & simple login demo
2022-07-05 12:33:00 【It Chunhe】
Catalog
1.1、 Write entity class Person
After learning jdbc, Use jdbc Little exercises to do
1、 Query... In the database person surface Encapsulate the queried data into Person Object returns
2、 Simple login logic judgment
1、 Package data return
Define a method , Inquire about person The table's data encapsulates it as an object , Then load the collection , return .
1. Definition Person class
2. Define methods public List<Person> findAll(){}
3. Implementation method select * from emp;
1.1、 Write entity class Person
package com.zhou.exercise;
public class Person {
private int id;
private String name;
private String email;
private String addr;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
1.2、 To write jdbc Code
package com.zhou.exercise;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JDBC_queryForObj {
public static void main(String[] args) {
// Calling method
List<Person> personList = findAll();
// Ergodic set
for (Person person : personList) {
System.out.println(person);
}
}
// Define a method to query data
public static List<Person> findAll() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// Define loading Person Set
List<Person> list = new ArrayList<Person>();
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///day10", "root", "123456");
String sql = "select * from person";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
Person person = new Person(); // take person Mention the outside
int id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
String addr = rs.getString(4);
person.setId(id);
person.setName(name);
person.setEmail(email);
person.setAddr(addr);
list.add(person);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// close resource
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// return list
return list;
}
}

2、 Simple login logic
1. Enter the user name and password through the keyboard
2. Determine whether the user has successfully logged in
package com.zhou.exercise;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JDBC_login {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(" Please enter a user name :");
String username = scanner.next();
System.out.println(" Please input a password :");
String password = scanner.next();
// Calling method Judge
boolean login = login(username, password);
if (login){
System.out.println(" Login successful !");
}else {
System.out.println(" Login failed !");
}
}
// Define a method to query data
public static boolean login(String username, String password) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// Define loading Person Set
List<Person> list = new ArrayList<Person>();
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///day10", "root", "123456");
String sql = "select * from user where username = ? and password = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
// rs.next The return value of is a Boolean value Just what we need true: Indicates that the current line is not the last line There's data false Indicates that the current line is the last line There's no data
// Indicates that the data queried is not empty Proof basis username and password Relevant records can be found
return rs.next();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// close resource
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false; // If try The inside is back Then changing the code will not execute
}
}

1、 Of course, here we find that many codes are highly repetitive Local laws that are almost used in addition, deletion, modification and inspection
Then we can extract the code into a tool class
2、 Our database connection information is in java In the code Caused and java Code coupling is dead
Then we can extract the connection information of the database into a configuration file
边栏推荐
- 【ijkplayer】when i compile file “compile-ffmpeg.sh“ ,it show error “No such file or directory“.
- MySQL log module of InnoDB engine
- Learn the memory management of JVM 02 - memory allocation of JVM
- MySQL function
- Migrate data from Mysql to neo4j database
- ZABBIX monitors mongodb (template and deployment operations)
- [superhard core] is the core technology of redis
- 一款新型的智能家居WiFi选择方案——SimpleWiFi在无线智能家居中的应用
- JS for loop number exception
- How can beginners learn flutter efficiently?
猜你喜欢

One article tells the latest and complete learning materials of flutter

MySQL splits strings for conditional queries

Detailed structure and code of inception V3

Solve the problem of cache and database double write data consistency

Interviewer: is acid fully guaranteed for redis transactions?

C language structure is initialized as a function parameter

Understand redis persistence mechanism in one article

16 channel water lamp experiment based on Proteus (assembly language)
![[figure neural network] GNN from entry to mastery](/img/e2/bb045fb03bc255b8659f9ca7cdd26b.jpg)
[figure neural network] GNN from entry to mastery

Pytoch implements tf Functions of the gather() function
随机推荐
Xi IO flow
Get the variable address of structure member in C language
Matlab imoverlay function (burn binary mask into two-dimensional image)
Want to ask, how to choose a securities firm? Is it safe to open an account online?
ABAP table lookup program
GNN(pytorch-geometric)
【ijkplayer】when i compile file “compile-ffmpeg.sh“ ,it show error “No such file or directory“.
Pytoch loads the initialization V3 pre training model and reports an error
UNIX socket advanced learning diary - advanced i/o functions
MySQL splits strings for conditional queries
Detailed steps for upgrading window mysql5.5 to 5.7.36
Correct opening method of redis distributed lock
Image hyperspectral experiment: srcnn/fsrcnn
MySQL stored procedure
ZABBIX ODBC database monitoring
Principle of universal gbase high availability synchronization tool in Nanjing University
语义分割实验:Unet网络/MSRC2数据集
NPM install reports an error
A guide to threaded and asynchronous UI development in the "quick start fluent Development Series tutorials"
Differences between IPv6 and IPv4 three departments including the office of network information technology promote IPv6 scale deployment