sqlite一个轻量级的数据库管理系统,当你的工程没那么复杂的时候,且需要到处移植的时候,不妨一试。
这里不多夸sqlite的优点了,感兴趣自行搜索。
在操作前,先定义db文件的地址:
val DB_FILENAME = "some.db"
然后使用Class.forName来对sqlite进行初始化:
Class.forName("org.sqlite.JDBC")
下面来创建一个表,id可以自增的:
val connection = DriverManager.getConnection("jdbc:sqlite:" + DB_FILENAME) val statement = connection.createStatement() System.out.println("open database successfully!") val sql = "CREATE TABLE some_table" + "(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + " mark CHAR(20) NOT NULL," + " path CHAR(200) NOT NULL," + " ymd CHAR(10) NOT NULL);" statement.executeUpdate(sql) System.out.println("create table some_table success!") statement.close() connection.close()
然后来插入一些数据:
val connection = DriverManager.getConnection("jdbc:sqlite:" + DB_FILENAME) val statement = connection.createStatement() val insertSql = "INSERT INTO some_table(mark, path, ymd) " + "VALUES ('mark1', 'path1', '20170902');" statement.executeUpdate(insertSql) val insertSql2 = "INSERT INTO some_table(mark, path, ymd) " + "VALUES ('mark2', 'path2', '20170903');" statement.executeUpdate(insertSql2) statement.close() connection.close()
来看看如何查询:
val connection = DriverManager.getConnection("jdbc:sqlite:" + DB_FILENAME) val statement = connection.createStatement() val selectSql = "SELECT * FROM somte_table;" val resultSet = statement.executeQuery(selectSql) while (resultSet.next()) { System.out.println(resultSet.getString("path")) } statement.close() connection.close()
先介绍到这儿了,其他删除等操作可查看具体的文档。