SQLite3簡介(An Introduction to SQLite3)

來源:互聯網
上載者:User

                    An Introduction to SQLite3(SQLite3簡介)                  
0.本文是對SQLite官方網站中的文檔以及介紹進行的簡要翻譯,主要介紹了SQLite的一些Features以及其常見的應用。

1.SQLite簡介
SQLite是實現了以下特徵的軟體:
i.Self-Contained:SQLite最大程度的實現了self-contained。它實現了對外部程式庫以及作業系統的最低要求,這使得它非常適合應用於嵌入式裝置,同時,可以應用於一些穩定的,很少修改配置的應用程式中。
SQLite是使用ANSI-C開發的,可以被任何的標準C編譯器來進行編譯。
SQLite與作業系統和存放裝置(磁碟)之間的通訊是通過VFS(Virtual File System)來完成的,對於嵌入式裝置來說,開發一個可用的VFS並不困難。
SQLite使用互斥來保證多線程環境下的操作安全性。
SQLite的原始碼是一個單一的C檔案-sqlite3.c,如果project需要使用它,只需要包含這個C檔案和對應的標頭檔(sqlite3.h)。

ii.Serverless:大多數SQL資料庫引擎都作為一個獨立的伺服器處理序,應用程式通過使用一些協議,比如TCP/IP來發送請求給伺服器,並接受結果,以這種方式來與資料庫伺服器進行通訊。SQLite與此不同,進程可以通過訪問資料庫直接進行資料庫檔案的讀寫而不需要中介層的伺服器處理序。這樣的實現的主要的好處是不需要進行安裝,配置,初始化,管理以及維護單獨的服務進程。但是,資料庫引擎可以通過使用伺服器來預防用戶端應用程式的bug,確保伺服器不被用戶端的錯誤所損壞。大多數SQL資料庫都是基於C/S模式的,在serverless的資料庫中,SQLite是目前唯一允許多個應用同時訪問的。

iii.Zero-Configuration:SQLite不需要任何配置---install、setup、configure server、administration、create instance、assign permissions、recover、troubleshooting。

iv.Transactional:SQLite實現了ACID(Atomic-原子性,Consistent-一致性,Isolated-隔離性,Durable-持久性)。SQLite實現了序列化事務來保證ACID,即使發生程式異常,作業系統異常或者電源故障。

v.Most Widely Deployed SQL Database:大多數資料庫是C/S模式的,而一台伺服器可以為很多人提供服務,而SQLite是嵌入式的資料庫軟體,大多數使用者會同時使用多個資料庫的拷貝。SQLite大量的被用於手機,PDA,MP3播放器以及機頂盒裝置。下面列舉了一些使用SQLite作為嵌入式伺服器的應用:
    Mozilla Firefox使用SQLite作為資料庫。
    Mac電腦中的包含了多份SQLite的拷貝,用於不同的應用。
    PHP將SQLite作為內建的資料庫。
    Skype用戶端軟體在內部使用SQLite。
    SymbianOS(智能手機操作平台的領航)內建SQLite。
    AOL郵件用戶端綁定了SQLite。
    Solaris 10在啟動過程中需要使用SQLite。
    McAfee殺毒軟體使用SQLite。
    iPhones使用SQLite。
    Symbian和Apple以外的很多手機生產廠商使用SQLite。
關於使用SQLite的Famous Users,請參考http://www.sqlite.org/famous.html

vi.OpenSource:SQLite處於public domain中,官方聲明如下:
Anyone is free to copy, modify, publish, use, compile, sell, or distribute the original SQLite code, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
一些其他的特色例如執行速度比C/S模式的資料庫引擎快、簡單易用、原始碼注釋良好、跨平台等請參考SQLite Features列表:
http://www.sqlite.org/features.html

2.SQLite的應用情境
SQLite具有小巧,快速和可靠的優點是源於其簡單-管理簡單,操作簡單,嵌入簡單以及維護自訂簡單。
當然,SQLite也有一些缺點,這取決於使用者的需求,SQLite不具有高度並發性,良好的存取許可權控制,沒有內建的函數集,不支援預存程序以及深奧的SQL語言特性(SQLite並不完全支援SQL92),不支援XML/Java擴充,不具有tera-byte或者peta-byte的延展性等等。所以,當需要上面列舉的這些功能時,SQLite就不在適合使用者了。SQLite不是企業級的RDBMS。
下面列舉了一些應用情境:
    應用檔案格式
    嵌入式裝置和應用
    中小型網站
    內建或者臨時資料庫
    命令列資料集分析工具
    作為企業資料庫的替代產品--demo階段或者測試階段
    教學
如果為了學習它,以備將來使用,或者要開發類似的應用情境,可以使用SQLite作為資料庫軟體。
企業級的RDBMS適用於C/S應用,高輸送量網站,非常大的資料集以及高度並發的應用。
關於SQLite區別於其他資料庫的特有屬性,請參考:http://www.sqlite.org/different.html

3.下載與使用
根據不同的平台,可以在下載頁面:http://www.sqlite.org/download.html下載對應的發布版本。筆者接下來將介紹SQLite在windows上的使用。多種程式設計語言可以通過使用wrapper或者driver來訪問SQLite,下面將介紹使用java程式設計語言來訪問SQLite並做一些常見的操作。
i.下載SQLite
windows版本的SQLite發布包解壓縮之後只是一個二進位的sqlite3.exe檔案。
可以直接運行該程式,即可進入sqlite3控制台(類似於mysql的控制台),可以通過輸入.help來擷取協助資訊。.quit可以推出控制台。控制台的一個簡單操作如下:
//可以直接使用sqlite3 databaseName來建立資料庫
//SQLite不支援create database,drop database這樣的語句,drop database時直接,刪除資料庫檔案即可。
E:/tools/sqlite>sqlite3.exe test<br />SQLite version 3.6.11<br />Enter ".help" for instructions<br />Enter SQL statements terminated with a ";"<br />sqlite> .help<br />.backup ?DB? FILE Backup DB (default "main") to FILE<br />.bail ON|OFF Stop after hitting an error. Default OFF<br />.databases List names and files of attached databases<br />//lots of other help information omitted here<br />.width NUM NUM ... Set column widths for "column" mode<br />sqlite> .databases<br />seq name file</p><p>--- --------------- ----------------------------------------------------------</p><p>0 main E:/tools/sqlite/test</p><p>sqlite> create table student(id varchar(10),name varchar(20),age smallint);<br />sqlite> select * from student;<br />sqlite> insert into student values('1001','lovesizhao',26);<br />sqlite> select * from student;<br />1001|lovesizhao|26<br />sqlite> drop table student;<br />sqlite> .quit<br />
這種直接在命令列提示符下面使用SQLite3的方式不是本文介紹的重點。
關於SQLite3支援的SQL文法相關內容如下:
SQLite3關鍵字:http://www.sqlite.org/lang_keywords.html
SQLite3支援的SQL文法:http://www.sqlite.org/lang.html
SQLite3不支援的SQL文法:http://www.sqlite.org/cvstrac/wiki?p=UnsupportedSql

ii.下載Java JDBC Driver for SQLite3
在下載頁面http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers,選擇下載JDBC Driver for SQLite3。
筆者使用的是SQLiteJDBC(http://www.xerial.org/trac/Xerial/wiki/SQLiteJDBC)。
該JDBC Driver的License是Apache Software Foundation 2.0 License。

iii.使用SQLite3資料庫
筆者使用了NetBeans作為開發環境,寫了簡單的Java類,註:筆者並非要講解SQLite3的所有功能以及細節的Features,只是作為一個介紹,如果有興趣的話,請更多的參考SQLite3官方網站及相關資源。
NetBeans的使用不屬於本文的介紹範圍。下面介紹兩個簡單的Java類。
筆者使用的SQLiteJDBC Driver版本為3.6.11。

SQLite3Util.java
package sqlite3;<br />import java.sql.Statement;<br />import java.sql.Connection;<br />import java.sql.DriverManager;<br />import java.sql.ResultSet;<br />import java.sql.SQLException;<br />import java.util.logging.Level;<br />import java.util.logging.Logger;</p><p>public final class SQLite3Util {</p><p> private final static String URL = "jdbc:sqlite:";<br /> private final static String TEST = "test";</p><p> private static Connection getConnection(String url) throws SQLException {<br /> Connection conn = null;<br /> try {<br /> Class.forName("org.sqlite.JDBC");<br /> conn = DriverManager.getConnection(url);</p><p> } catch (ClassNotFoundException ex) {<br /> Logger.getLogger(SQLite3Util.class.getName()).log(Level.SEVERE, null, ex);<br /> } finally {<br /> return conn;<br /> }<br /> }</p><p> public static Connection getSQLite3Connection() throws SQLException {<br /> return getConnection(URL + TEST);<br /> }</p><p> public static Connection getSQLite3Connection(String database) throws SQLException {<br /> //Here database can be database name, database file name or memory:<br /> //Connection connection = DriverManager.getConnection("jdbc:sqlite:C:/work/mydatabase.db");<br /> //Connection connection = DriverManager.getConnection("jdbc:sqlite:/home/leo/work/mydatabase.db");<br /> //Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:");<br /> return getConnection(URL + ((database == null || database.equals("")) ? TEST : database));<br /> }</p><p> public static void close(Connection conn, Statement stmt, ResultSet rs) throws SQLException {<br /> if (conn != null) {<br /> conn.close();<br /> }<br /> if (stmt != null) {<br /> stmt.close();<br /> }<br /> if (rs != null) {<br /> rs.close();<br /> }<br /> }</p><p> public static void closeQuiet(Connection conn, Statement stmt, ResultSet rs) {<br /> try {<br /> if (conn != null) {<br /> conn.close();<br /> }<br /> } catch (SQLException e) {<br /> Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);<br /> }<br /> try {<br /> if (stmt != null) {<br /> stmt.close();<br /> }<br /> } catch (SQLException e) {<br /> Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);<br /> }<br /> try {<br /> if (rs != null) {<br /> rs.close();<br /> }<br /> } catch (SQLException e) {<br /> Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);<br /> }<br /> }<br />}</p><p>
SQLite3Test.java

package sqlite3;</p><p>import java.sql.Statement;<br />import java.sql.Connection;<br />import java.sql.DatabaseMetaData;<br />import java.sql.ResultSet;<br />import java.sql.SQLException;<br />import java.util.logging.Level;<br />import java.util.logging.Logger;</p><p>public class SQLite3Test {</p><p> /**<br /> * @param args the command line arguments<br /> */<br /> public static void main(String[] args) {<br /> // declare and initialize database names and java.sql objects<br /> Connection conn = null;<br /> Statement stmt = null;<br /> ResultSet rs = null;<br /> String studentDB = "D:/NetBeans/NetbeansProjects/SQLite3/student.db";<br /> String inmemoryDB = ":memory:";</p><p> // the dbmd is used to check what SQLite3JDBC driver provide for JDBC<br /> DatabaseMetaData dbmd = null;</p><p> try {<br /> // get connection to default database:test<br /> conn = SQLite3Util.getSQLite3Connection();<br /> if (conn == null) {<br /> return;<br /> }<br /> dbmd = conn.getMetaData();<br /> // just print information to standard console instead of output file<br /> System.out.println("DatabaseProductName:" + dbmd.getDatabaseProductName());<br /> System.out.println("SQLKeywords:" + dbmd.getSQLKeywords());<br /> System.out.println("JDBCMajorVersion:" + dbmd.getJDBCMajorVersion());<br /> System.out.println("JDBCMinorVersion:" + dbmd.getJDBCMinorVersion());</p><p> // get connection to database:D:/NetBeans/NetbeansProjects/SQLite3/student.db<br /> conn = SQLite3Util.getSQLite3Connection(studentDB);<br /> stmt = conn.createStatement();<br /> stmt.executeUpdate("drop table if exists student.student");<br /> stmt.executeUpdate("create table student(id smallint primary key, name varchar(20))");<br /> stmt.executeUpdate("insert into student values(1,'zhangzhongliang')");<br /> stmt.executeUpdate("insert into student values(2,'liusizhao')");<br /> rs = stmt.executeQuery("select * from student");<br /> int i = 1;<br /> while (rs.next()) {<br /> System.out.println("row no=" + i);<br /> System.out.println("id=" + rs.getInt("id"));<br /> System.out.println("name=" + rs.getString("name"));<br /> i++;<br /> }<br /> stmt.executeUpdate("drop table student");</p><p> // get connection to database in memory<br /> // this will not create a database data file in your disk<br /> conn = SQLite3Util.getSQLite3Connection(inmemoryDB);<br /> stmt = conn.createStatement();<br /> stmt.executeUpdate("drop table if exists student.student");<br /> stmt.executeUpdate("create table student(id smallint primary key, name varchar(20))");<br /> stmt.executeUpdate("insert into student values(1,'zhangzhongliang')");<br /> stmt.executeUpdate("insert into student values(2,'liusizhao')");<br /> rs = stmt.executeQuery("select * from student");<br /> i = 1;<br /> while (rs.next()) {<br /> System.out.println("row no=" + i);<br /> System.out.println("id=" + rs.getInt("id"));<br /> System.out.println("name=" + rs.getString("name"));<br /> i++;<br /> }<br /> stmt.executeUpdate("drop table student");<br /> } catch (SQLException ex) {<br /> Logger.getLogger(SQLite3Test.class.getName()).log(Level.SEVERE, null, ex);<br /> } finally {<br /> SQLite3Util.closeQuiet(conn, stmt, rs);<br /> }<br /> }<br />}</p><p>
4.小結
本文主要介紹了SQLite3作為資料庫軟體,與其他資料庫不同的特性,優缺點以及應用情境的選擇。最後通過使用JDBC Driver進行了一個簡單的程式測試,介紹了如何通過JDBC來訪問SQLite資料庫。

5.參考資料
SQLite官方地址:http://sqlite.org/
SQLite文檔:http://sqlite.org/docs.html
SQLite JDBC Driver:http://www.xerial.org/trac/Xerial/wiki/SQLiteJDBC
Java JDBC:http://java.sun.com/products/jdbc/overview.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.