小言_互联网的博客

SQLite之 JDBC入门

719人阅读  评论(0)

SQLite是一种C语言库,实现了一个 小型, 快速, 自包含, 高可靠性, 功能齐全的 SQL数据库引擎。本身不提供java接口,如果需要通过java连接SQLite数据库,则需要SQLite JDBC驱动程序,来充当媒介。

由Taro L. Saito开发的SQLite JDBC驱动程序是Zentus SQLite JDBC驱动程序的扩展,使Java能够访问SQLite数据库文件。Xerial版本的SQLiteJDBC库不需要进行配置,在任何OS环境中均可运行,Windows,Mac OS X,Linux和纯Java SQLite的所有本机库都被组装到一个JAR(Java存档)中文件。Xerial版本的SQLiteJDBC相比较最初的Zentus的SQLite JDBC驱动程序,用户不需要使用命令行参数(例如-Djava.library.path =)来设置本机代码(dll,jnilib,so文件,它们是JNDI C程序)的路径等参数。

1.使用方式

SQLiteJDBC有多种使用方式,本文介绍2种:jar运行方式和maven方式

1. 1 jar独立方式

如果没有指定路径,默认db文件存储在System.getProperty("java.io.tmpdir").

编写测试文件 Sample.java


  
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. public class Sample
  7. {
  8. public static void main(String[] args) throws ClassNotFoundException
  9. {
  10. // load the sqlite-JDBC driver using the current class loader
  11. Class.forName( "org.sqlite.JDBC");
  12. Connection connection = null;
  13. try
  14. {
  15. // create a database connection
  16. connection = DriverManager.getConnection( "jdbc:sqlite:sample.db");
  17. Statement statement = connection.createStatement();
  18. statement.setQueryTimeout( 30); // set timeout to 30 sec.
  19. statement.executeUpdate( "drop table if exists person");
  20. statement.executeUpdate( "create table person (id integer, name string)");
  21. statement.executeUpdate( "insert into person values(1, 'leo')");
  22. statement.executeUpdate( "insert into person values(2, 'yui')");
  23. ResultSet rs = statement.executeQuery( "select * from person");
  24. while(rs.next())
  25. {
  26. // read the result set
  27. System.out.println( "name = " + rs.getString( "name"));
  28. System.out.println( "id = " + rs.getInt( "id"));
  29. }
  30. }
  31. catch(SQLException e)
  32. {
  33. // if the error message is "out of memory",
  34. // it probably means no database file is found
  35. System.err.println(e.getMessage());
  36. }
  37. finally
  38. {
  39. try
  40. {
  41. if(connection != null)
  42. connection.close();
  43. }
  44. catch(SQLException e)
  45. {
  46. // connection close failed.
  47. System.err.println(e);
  48. }
  49. }
  50. }
  51. }

编译Sample.java

 javac Sample.java

运行java文件,确保之前下载的sqlite-jdbc-(VERSION).jar在当前目录,


  
  1. > java -classpath ".;sqlite-jdbc-(VERSION).jar" Sample # in Windows
  2. > java -classpath ".:sqlite-jdbc-(VERSION).jar" Sample # in Mac or Linux

输出 


  
  1. name = leo
  2. id = 1
  3. name = yui
  4. id = 2

1.2 maven方式

maven方式与其他通过maven构建的没有什么区别,直接添加依赖即可。


  
  1. <dependency>
  2. <groupId>org.xerial</groupId>
  3. <artifactId>sqlite-jdbc</artifactId>
  4. <version> 3.30.1</version>
  5. </dependency>

2.常见问题

2.1 加载外部db

因为,SQLite 文件格式稳定,跨平台且向后兼容,开发人员保证至少在2050年之前保持这种格式。SQLite数据库文件通常用作在系统之间传输丰富内容的容器并作为数据的长期存档格式 。我们可以加载其他平台的db直接使用

Windows中加载,file C:\work\mydatabase.db

Connection connection = DriverManager.getConnection("jdbc:sqlite:C:/work/mydatabase.db");

其他平台 UNIX (Linux, Mac OS X, etc ) file /home/leo/work/mydatabase.db

Connection connection = DriverManager.getConnection("jdbc:sqlite:/home/leo/work/mydatabase.db");

Java package中 


  
  1. Connection conn = DriverManager.getConnection( "jdbc:sqlite::resource:org/yourdomain/sample.db");
  2. Connection conn = DriverManager.getConnection( "jdbc:sqlite::resource:jar:http://www.xerial.org/svn/sqlite-jdbc/src/test/resources/testdb.jar!/sample.db");

远程服务器中 

Connection conn = DriverManager.getConnection("jdbc:sqlite::resource:http://www.xerial.org/svn/project/XerialJ/trunk/sqlite-jdbc/src/test/java/org/sqlite/sample.db"); 

 

2.2 Memory方式

SQLite数据库通常存储在单个普通磁盘文件中。但是,在某些情况下,数据库可能存储在内存中。完成此操作后,不会打开任何磁盘文件。而是纯粹在内存中创建一个新数据库。一旦数据库连接关闭,该数据库将不复存在。

Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:");

2.3 连接配置

SQLite默认支持需要配置,我们可以通过配置参数来更好使用和优化。


  
  1. SQLiteConfig config = new SQLiteConfig();
  2. // 设置共享缓存
  3. //这允许单独的数据库连接共享相同的内存数据库。当然,共享内存数据库的所有数据库连接都必
  4. //须处于同一进程中。当与数据库的最后一个连接关闭时,数据库将被自动删除并回收内存。
  5. config.setSharedCache( true);
  6. //设置数据库的读写模式
  7. config.setReadOnly( boolean readOnly)
  8. //更改每次打开数据库文件时SQLite将在内存中同时保存的数据库磁盘页的最大数量。
  9. config.setCacheSize( int numberOfPages)
  10. Connection conn = DriverManager.getConnection( "jdbc:sqlite:sample.db", config.toProperties());
除此之外,还可以通过set(Pragma pragma, boolean flag) 手动设置一些参数 ,详细可以参考官网配置

  
  1. // Parameters requiring SQLite3 API invocation
  2. OPEN_MODE( "open_mode", "Database open-mode flag", null),
  3. SHARED_CACHE( "shared_cache", "Enable SQLite Shared-Cache mode, native driver only", OnOff),
  4. LOAD_EXTENSION( "enable_load_extension", "Enable SQLite load_extention() function, native driver only", OnOff),
  5. // Pragmas that can be set after opening the database
  6. CACHE_SIZE( "cache_size"),
  7. MMAP_SIZE( "mmap_size"), //内存映射模式
  8. CASE_SENSITIVE_LIKE( "case_sensitive_like", OnOff),
  9. COUNT_CHANGES( "count_changes", OnOff),
  10. DEFAULT_CACHE_SIZE( "default_cache_size"),
  11. DEFER_FOREIGN_KEYS( "defer_foreign_keys", OnOff),
  12. EMPTY_RESULT_CALLBACKS( "empty_result_callback", OnOff),
  13. ENCODING( "encoding", toStringArray(Encoding.values())),
  14. FOREIGN_KEYS( "foreign_keys", OnOff),
  15. FULL_COLUMN_NAMES( "full_column_names", OnOff),
  16. FULL_SYNC( "fullsync", OnOff),
  17. INCREMENTAL_VACUUM( "incremental_vacuum"),
  18. JOURNAL_MODE( "journal_mode", toStringArray(JournalMode.values())),
  19. JOURNAL_SIZE_LIMIT( "journal_size_limit"),
  20. LEGACY_FILE_FORMAT( "legacy_file_format", OnOff),
  21. LOCKING_MODE( "locking_mode", toStringArray(LockingMode.values())),
  22. PAGE_SIZE( "page_size"),
  23. MAX_PAGE_COUNT( "max_page_count"),
  24. READ_UNCOMMITED( "read_uncommited", OnOff),
  25. RECURSIVE_TRIGGERS( "recursive_triggers", OnOff),
  26. REVERSE_UNORDERED_SELECTS( "reverse_unordered_selects", OnOff),
  27. SECURE_DELETE( "secure_delete", new String[] { "true", "false", "fast" }),
  28. SHORT_COLUMN_NAMES( "short_column_names", OnOff),
  29. SYNCHRONOUS( "synchronous", toStringArray(SynchronousMode.values())),
  30. TEMP_STORE( "temp_store", toStringArray(TempStore.values())),
  31. TEMP_STORE_DIRECTORY( "temp_store_directory"),
  32. USER_VERSION( "user_version"),
  33. APPLICATION_ID( "application_id"),
  34. // Others
  35. TRANSACTION_MODE( "transaction_mode", toStringArray(TransactionMode.values())),
  36. DATE_PRECISION( "date_precision", "\"seconds\": Read and store integer dates as seconds from the Unix Epoch (SQLite standard).\n\"milliseconds\": (DEFAULT) Read and store integer dates as milliseconds from the Unix Epoch (Java standard).", toStringArray(DatePrecision.values())),
  37. DATE_CLASS( "date_class", "\"integer\": (Default) store dates as number of seconds or milliseconds from the Unix Epoch\n\"text\": store dates as a string of text\n\"real\": store dates as Julian Dates", toStringArray(DateClass.values())),
  38. DATE_STRING_FORMAT( "date_string_format", "Format to store and retrieve dates stored as text. Defaults to \"yyyy-MM-dd HH:mm:ss.SSS\"", null),
  39. BUSY_TIMEOUT( "busy_timeout", null),
  40. HEXKEY_MODE( "hexkey_mode", toStringArray(HexKeyMode.values())),
  41. PASSWORD( "password", null);

 


转载:https://blog.csdn.net/wank1259162/article/details/104946744
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场