当前位置:网站首页>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();
}
}
}
}
边栏推荐
- Seven major technical updates that developers should pay most attention to on build 2022
- 3D打印机穿线:5种简单的解决方案
- OpenGL es: (4) detailed explanation of EGL API (Continued)
- PLA不粘貼在床上:6個簡單的解决方案
- Make Tiantou village sweet. Is Xianjing taro or cabbage the characteristic agricultural product of Tiantou Village
- jdbc 数据库操作
- 穿越派 你的数据云行
- 云盘里资料被和谐了,怎么办?
- srpingboot security demo
- OpenGL es: (2) relationship between OpenGL es, EGL and glsl
猜你喜欢

Don't put your notes and videos everywhere!

Seven major technical updates that developers should pay most attention to on build 2022

68 cesium code datasource loading czml

3D打印机穿线:5种简单的解决方案

【文件系统】如何在ubi之上运行squashfs
![Pit of kotlin bit operation (bytes[i] and 0xff error)](/img/2c/de0608c29d8af558f6f8dab4eb7fd8.png)
Pit of kotlin bit operation (bytes[i] and 0xff error)

Make Tiantou village sweet. Is Xianjing taro or cabbage the characteristic agricultural product of Tiantou Village

Multi label lsml for essay learning records

Cjc8988 Low Power Stereo codec with 2 stereo headphone drivers

How to transmit and share 4GB large files remotely in real time?
随机推荐
jdbc 数据库操作
Servlet
基于LabVIEW的计时器
Oracle create user + Role
不是你脑子不好用,而是因为你没有找到对的工具
2022 年面向初学者的 10 大免费 3D 建模软件
What if the data in the cloud disk is harmonious?
π盘,让您电脑变成个人的私有云
穿越派·派盘 + 思源笔记 = 私人笔记本
PLA不粘貼在床上:6個簡單的解决方案
Preliminary level of C language -- selected good questions on niuke.com
扩展点系列之SmartInstantiationAwareBeanPostProcessor确定执行哪一个构造方法 - 第432篇
Stack Title: parsing Boolean expressions
TIDB数据库特性总结
SystemVerilog学习-06-类的封装
穿越派·派盘 + Mountain Duck = 数据本地管理
freeswitch拨打分机号
3D打印机穿线:5种简单的解决方案
从诺奖知“边缘计算”的未来!
让厦门灌口镇田头村变“甜头”村的特色农产品之一是