springboot如何对本地数据库增删改查_SpringBoot使用JDBC实现增删改查

一、项目分层

二、连接数据库

步骤一、引入连接数据库的相关依赖

org.springframework.boot

spring-boot-starter-jdbc

com.alibaba

druid

1.1.14

mysql

mysql-connector-java

8.0.15

org.projectlombok

lombok

1.18.6

provided

步骤二、配置数据库连接池相关信息

步骤三、初始化数据库连接

@Configuration

@PropertySource(value = "classpath:application.properties")

public class DataSourceConfiguration {

@Bean(destroyMethod = "close", initMethod = "init")

@ConfigurationProperties(prefix = "spring.datasource")

public DataSource druidDataSource() {

DruidDataSource druidDataSource = new DruidDataSource();

return druidDataSource;

}

}

启动报错:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

步骤四、增删改查

1、新增

/**

* 新增用户

* @param user 用户信息

* @return

*/

@Override

public int add(User user) {

String sql = "insert into sys_user (user_name,password,email,telephone) values(?,?,?,?)";

int result = jdbcTemplate.update(sql, user.getUserName(),user.getPassword(),user.getEmail(),user.getTelephone());

return result;

}

2、修改

/**

* 修改用户 用户信息

* @param user

* @return

*/

@Override

public int update(User user) {

String sql = "update sys_user set user_name =?,password=?,email=?,telephone=? where id = ?";

int result = jdbcTemplate.update(sql, user.getUserName(),user.getPassword(),user.getEmail(),user.getTelephone(),user.getId());

return result;

}

3、删除

/**

* 删除用户

* @param id 用户id

* @return

*/

@Override

public int deleteById(String id) {

String sql = "delete from sys_user where id = ?";

int result = jdbcTemplate.update(sql, id);

return result;

}

4、根据用户id获取用户

/**

* 根据用户id获取用户

* @param id 用户id

* @return

*/

@Override

public User getUserById(String id) {

String sql="select * from sys_user where id=?";

return jdbcTemplate.queryForObject(sql, new RowMapper() {

@Override

public User mapRow(ResultSet rs, int rowNum) throws SQLException {

return User.builder()

.id(rs.getInt(1))

.userName(rs.getString(2))

.password(rs.getString(3))

.email(rs.getString(4))

.telephone(rs.getString(5))

.build();

}

}, id);

}

注意:

1、接收参数的两种方式

(1)参数在路径上

(2)问号传参

你可能感兴趣的:(springboot如何对本地数据库增删改查_SpringBoot使用JDBC实现增删改查)