当前位置:网站首页>JDBC database operation
JDBC database operation
2022-07-01 06:06:00 【Fat man smiles】
Operate on this database

1, stay pom file dependencies Internal configuration dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
2, Writing user entity classes
// Here we use lombok The plug-in automatically generates for each property get and set Method , There are also parametric and nonparametric functions . Import code in “1”
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Accessors(chain = true) // Chain programming
public class User {
private int id;
private String userName;
private String userPass;
}
3, Write user interface
public interface UserDao {
// Insert
void insert(User user) throws Exception;
// modify
int update(User user) throws Exception;
// Delete
int delete(int id) throws Exception;
}
4, Implementation class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class UserDaoImpl implements UserDao{
// establish conection
private final String url = "jdbc:mysql://localhost:3306/aad?useSSL=false&charactorEncoding=utf8";
private final String user1 = "root";
private final String password = "123456";
// Insert
@Override
public void insert(User user) throws Exception{
// Load drive class
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user1,password);
// Intercostal statement object
String sql = "insert into admin(userName,userPass) values(?,?)";
PreparedStatement pstm = con.prepareStatement(sql);
// Set parameters
pstm.setString(1, user.getUserName());
pstm.setString(2,user.getUserPass());
// perform sql
int r = pstm.executeUpdate();
// Output
System.out.println(r);
// close resource
pstm.close();
con.close();
}
// modify
@Override
public int update(User user) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user1,password);
String sql = "update admin set userName = ?, userPass = ? where id = ?";
PreparedStatement pstm = con.prepareStatement(sql);
pstm.setString(1,user.getUserName());
pstm.setString(2,user.getUserPass());
pstm.setInt(3,user.getId());
int r = pstm.executeUpdate();
pstm.close();
con.close();
return r;
}
// Delete
@Override
public int delete(int id) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user1,password);
String sql = "delete from admin where id = ?";
PreparedStatement pstm = con.prepareStatement(sql);
pstm.setInt(1,id);
int r = pstm.executeUpdate();
return r;
}
}
5, Use junit test
① Insert the test
import org.junit.Test;
public class UserDaoImplTest {
// Insert the test
@Test
public void testInsert() throws Exception{
User user = new User()
.setUserName(" wuhu ")
.setUserPass("123456");
UserDao userDao = new UserDaoImpl();
userDao.insert(user);
}
}
You can see the successful insertion 
② Revision Test
// Revision Test
@Test
public void testUpdate() throws Exception {
User user = new User()
.setId(1)
.setUserName(" Xiao Ming ")
.setUserPass("55555");
userDao.update(user);
}

You can see id by 1 User modification of succeeded !
③ Delete the test
// Delete the test
@Test
public void testDelete() throws Exception {
int id = 2;
userDao.delete(id);
}
id by 2 The data is deleted 
ps: The first time to write all the code that has a lot of repetition , The encapsulation will be modified later .
6, Improved encapsulation of duplicate code , Write a tool class
Create a jdbcutil class
public final class jdbcUtil01 {
private static final String url = "jdbc:mysql://localhost:3306/aad?useSSL=false&charactorEncoding=utf8";
private static final String user1 = "root";
private static final String password = "123456";
private jdbcUtil01() {
}
// Load drive class , Just execute it once , There is no need to return
static {
try {
Class.forName("com.mysql.jdbc.Driver");
}catch (Exception e) {
//e.printStackTrace();
throw new RuntimeException(" Error loading drive class , The error message is " + e.getMessage());
}
}
public static int update(String sql, Object... params) {
Connection con =null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
// Load drive class
Class.forName("com.mysql.jdbc.Driver");
// Create connection objects
con = DriverManager.getConnection(url,user1,password);
// Create execution sql Statement object
pstm = con.prepareStatement(sql);
// Set parameters
for(int i = 0; i < params.length; i++) {
pstm.setObject(i + 1,params[i]);
}
// perform sql
return pstm.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
return 0;
}finally {
distory(con,pstm,rs);
}
}
// A common way to free up resources .
public static void distory(Connection con, PreparedStatement pstm, ResultSet rs) {
// Release resources
if(rs != null) {
try{
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(pstm != null) {
try{
pstm.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(con != null) {
try{
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
边栏推荐
猜你喜欢
随机推荐
Beauty of Mathematics - Application of Mathematics
SOE spatial analysis server MySQL and PostGIS geospatial database of Postgres anti injection attack
SOE空间分析服务器 MySQL以及PostGres的地理空间库PostGIS防注入攻击
restframework-simpleJWT重写认证机制
Some errors encountered in MySQL data migration
ArcServer密码重置(账号不可以重置)
SystemVerilog学习-08-随机约束和线程控制
Infinite horizontal marble game
DEV XPO对比之XAF BO
Arcserver password reset (account cannot be reset)
c# Xml帮助类
OpenGL ES: (4) EGL API详解 (转)
OpenGL ES: (5) OpenGL的基本概念、OpenGL ES 在屏幕产生图片的过程、OpenGL管线(pipeline)
Linux closes the redis process SYSTEMd+
Code shoe set - mt3149 · and - the data is not very strong. Violent pruning can deceive AC
Debug details under pycharm
On the first day of the new year, 3000 Apache servers went down
excel初级应用案例——杜邦分析仪
Make Tiantou village sweet. Is Xianjing taro or cabbage the characteristic agricultural product of Tiantou Village
MinIO纠错码、分布式MinIO集群搭建及启动









