当前位置:网站首页>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();
}
}
}
}
边栏推荐
- TiDB单机模拟部署生产环境集群(闭坑实践,亲测有效)
- SystemVerilog学习-07-类的继承和包的使用
- How to transmit and share 4GB large files remotely in real time?
- Leetcode Max rectangle, Max square series 84 85. 221. 1277. 1725. (monotonic stack, dynamic programming)
- CJC8988带2个立体声耳机驱动器的低功率立体声编解码器
- Freeswitch dial the extension number
- 论文学习记录随笔 多标签之LSML
- Dear pie users, I want to confess to you!
- Linux closes the redis process SYSTEMd+
- FPGA - 7系列 FPGA内部结构之Clocking -02- 时钟布线资源
猜你喜欢

Continue to learn MySQL

Debug details under pycharm

Advanced drawing skills of Excel lecture 100 (1) - use Gantt chart to show the progress of the project

为了保护自己的数据,他奋斗了一天一夜

OpenGL ES: (5) OpenGL的基本概念、OpenGL ES 在屏幕产生图片的过程、OpenGL管线(pipeline)

What if the data in the cloud disk is harmonious?

C language beginner level - realize the minesweeping game

机械臂速成小指南(六):步进电机驱动器

freeswitch拨打分机号

从诺奖知“边缘计算”的未来!
随机推荐
SystemVerilog学习-09-进程间同步、通信和虚方法
69 Cesium代码datasource加载geojson
excel初级应用案例——杜邦分析仪
LED lighting used in health lighting
How to transmit and share 4GB large files remotely in real time?
让厦门灌口镇田头村变甜头村的特色农产品之一是蚂蚁新村
Don't put your notes and videos everywhere!
Fixed height of the first column in El table dynamic header rendering
Crossing pie · pie pan + Mountain duck = local data management
Oracle 序列+触发器
相同区域 多源栅格数据 各个像元行列号一致,即行数列数相同,像元大小相同
OpenGL es: (2) relationship between OpenGL es, EGL and glsl
OpenGL es: (4) detailed explanation of EGL API (Continued)
蚂蚁新村田头村变甜头村 让厦门灌口镇田头村变甜头村的特色农产品之一是
OpenGL es: (1) origin of OpenGL es (transfer)
Index method and random forest to realize the information of surface water body in wet season in Shandong Province
芯片,建立在沙粒上的帝国!
云盘里资料被和谐了,怎么办?
This is the necessary software for college students 𞓜 knowledge management
Codeforces Round #803 (Div. 2)vp