什么是Sqlite3
sqlite3是一个进程内的库,实现了自给自足、无服务器、零配置、事务性的SQL数据库引擎。它是一个增长最快的数据库引擎。它不是一个独立的进程,可以按应用程序需求进行静态或动态连接,SQLite直接访问其存储文件。
为什么要使用Sqlite3
- 不需要一个单独的服务器进程或操作的系统(无服务器的)。
- SQLite 不需要配置,这意味着不需要安装或管理。
- 一个完整的 SQLite 数据库是存储在一个单一的跨平台的磁盘文件。
- SQLite 是非常小的,是轻量级的,完全配置时小于 400KiB,省略可选功能配置时小于250KiB。
- SQLite 是自给自足的,这意味着不需要任何外部的依赖。
- SQLite 事务是完全兼容 ACID 的,允许从多个进程或线程安全访问。
- SQLite 支持 SQL92(SQL2)标准的大多数查询语言的功能。
- SQLite 使用 ANSI-C 编写的,并提供了简单和易于使用的 API。
- SQLite 可在 UNIX(Linux, Mac OS-X, Android, iOS)Windows(Win32, WinCE, WinRT)中运行。
在SpringBoot项目中使用Sqlite3
引入依赖包
<!-- sqlite3驱动包 -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.44.1.0</version>
</dependency>
<!--mybatis-plus插件-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
application.yml配置
spring:
datasource:
driver-class-name: org.sqlite.JDBC
url: jdbc:sqlite:C:\Users\28604\Desktop\sqlite\demo\src\main\resources\db\database1.db
# url: jdbc:sqlite::resource:db/database1.db #此方式为相对路径写法,必须放到resource目录下
username:
password:
logging:
level:
com.example.demo.domain.mapper: DEBUG
创建实体类
@Data
public class User {
@TableId(type = IdType.AUTO)
private Integer id;
private String name;
}
创建UserMapper映射类
@Mapper
public interface UserMapper extends BaseMapper<User> {} // 结合mybatis plus
创建Controller测试类
@RestController
public class TestController {
@Autowired
UserMapper userMapper;
/** 增添数据 */
@PostMapping("/insert")
public Object insert(String name) {
User user = new User();
user.setName(name);
return userMapper.insert(user);
}
/** 查询数据 */
@GetMapping("/show")
public Object show() {
return userMapper.selectList(null);
}
/** 删除数据 */
@DeleteMapping("/delete")
public Object delete(Integer id) {
return userMapper.deleteById(id);
}
/** 修改数据 */
@PutMapping("update")
public Object update(Integer id, String name) {
User user = new User();
user.setId(id);
user.setName(name);
return userMapper.updateById(user);
}
}
测试,成功插入并查询到数据
坑点
在生产环境中使用sqlite的时候数据库路径必须是绝对路径,因为最后会打包成jar包,jar是一个压缩包,数据文件不可修改,如果用相对路径的数据库文件的话重启服务会发现数据会被清空。
标签:SQLite,name,userMapper,sqlite,Sqlite3,Plus,user,Mybatis,public From: https://blog.csdn.net/2301_76788095/article/details/139574047