Mixed SQLite with Bukkit to build a powerful Data storage layer
编写 Bukkit 和 Spigot 插件时,经常遇到存储永久数据困难的情况,大多时候我会用 JSON 来解决此问题,但是 JSON 经常出现读写速度慢、代码复杂的情况,但可以达到相同目标的 SQLite 数据库能轻松解决问题,可以尝试使用下面的方法对 SQLite 进行控制(另外,此方法全 Java 工程通用):
⭐控制类 SQLite.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| public class SQLite { public static Connection getConnection() throws SQLException { SQLiteConfig config = new SQLiteConfig(); config.setSharedCache(true); config.enableRecursiveTriggers(true); SQLiteDataSource ds = new SQLiteDataSource(config); ds.setUrl("jdbc:sqlite:Database.db"); return ds.getConnection(); }
public void createTable(Connection con)throws SQLException { String sql = "DROP TABLE IF EXISTS NUMBERS ;create table NUMBERS (english String, chinese String); "; Statement stat = null; stat = con.createStatement(); stat.executeUpdate(sql);
}
public void dropTable(Connection con)throws SQLException { String sql = "drop table NUMBERS "; Statement stat = null; stat = con.createStatement(); stat.executeUpdate(sql); }
public void insert(Connection con, String english, String chinese)throws SQLException { String sql = "insert into NUMBERS (english, chinese) values(?,?)"; PreparedStatement pst = null; pst = con.prepareStatement(sql); int idx = 1 ; pst.setString(idx++, uuid.toString()); pst.setString(idx++, sqlite); pst.executeUpdate();
}
public void update(Connection con, String english, String chinese)throws SQLException { String sql = "update NUMBERS set chinese = ? where english = ?"; PreparedStatement pst = null; pst = con.prepareStatement(sql); int idx = 1 ; pst.setString(idx++, sqlite); pst.setString(idx++, uuid.toString()); pst.executeUpdate(); }
public void delete(Connection con, Stirng english)throws SQLException { String sql = "delete from NUMBERS where english = ?"; PreparedStatement pst = null; pst = con.prepareStatement(sql); int idx = 1 ; pst.setString(idx++, uuid.toString()); pst.executeUpdate(); } public static void selectAll(Connection con)throws SQLException { String sql = "select * from NUMBERS"; Statement stat = null; ResultSet rs = null; stat = con.createStatement(); rs = stat.executeQuery(sql); while(rs.next()) { String uuid = rs.getString("english"); String sqlite = rs.getString("chinese"); System.out.println(rs.getString("english")+"\t"+rs.getString("chinese")); } } }
|
⭐使用案例【测试性案例】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import SQLite; public static void main(String args[]) throws SQLException { SQLite sqlite = new SQLite(); Connection con = sqlite.getConnection(); sqlite.createTable(con); sqlite.insert(con, "First", "一"); sqlite.insert(con, "Second", "二"); sqlite.selectAll(con); sqlite.update(con, "First", "壹"); sqlite.delete(con, 1); sqlite.dropTable(con); con.close(); }
|