SQLite3简介

  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  
SQLite version 3.6.11  
Enter ".help" for instructions  
Enter SQL statements terminated with a ";" 
sqlite> .help  
.backup ?DB? FILE      Backup DB (default "main") to FILE  
.bail ON|OFF           Stop after hitting an error.  Default OFF  
.databases             List names and files of attached databases  
//lots of other help information omitted here  
.width NUM NUM ...     Set column widths for "column" mode  
sqlite> .databases  
seq  name             file  
 
---  ---------------  ----------------------------------------------------------  
 
0    main             E:/tools/sqlite/test  
 
sqlite> create table student(id varchar(10),name varchar(20),age smallint);  
sqlite> select * from student;  
sqlite> insert into student values('1001','lovesizhao',26);  
sqlite> select * from student;  
1001|lovesizhao|26  
sqlite> drop table student;  
sqlite> .quit 
E:/tools/sqlite>sqlite3.exe test
SQLite version 3.6.11
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .help
.backup ?DB? FILE      Backup DB (default "main") to FILE
.bail ON|OFF           Stop after hitting an error.  Default OFF
.databases             List names and files of attached databases
//lots of other help information omitted here
.width NUM NUM ...     Set column widths for "column" mode
sqlite> .databases
seq  name             file

---  ---------------  ----------------------------------------------------------

0    main             E:/tools/sqlite/test

sqlite> create table student(id varchar(10),name varchar(20),age smallint);
sqlite> select * from student;
sqlite> insert into student values('1001','lovesizhao',26);
sqlite> select * from student;
1001|lovesizhao|26
sqlite> drop table student;
sqlite> .quit
 
这种直接在命令行提示符下面使用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;  
import java.sql.Statement;  
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.util.logging.Level;  
import java.util.logging.Logger;  
 
 
public final class SQLite3Util {  
 
    private final static String URL = "jdbc:sqlite:";  
    private final static String TEST = "test";  
 
    private static Connection getConnection(String url) throws SQLException {  
        Connection conn = null;  
        try {  
            Class.forName("org.sqlite.JDBC");  
            conn = DriverManager.getConnection(url);  
 
        } catch (ClassNotFoundException ex) {  
            Logger.getLogger(SQLite3Util.class.getName()).log(Level.SEVERE, null, ex);  
        } finally {  
            return conn;  
        }  
    }  
 
    public static Connection getSQLite3Connection() throws SQLException {  
        return getConnection(URL + TEST);  
    }  
 
    public static Connection getSQLite3Connection(String database) throws SQLException {  
        //Here database can be database name, database file name or memory:  
        //Connection connection = DriverManager.getConnection("jdbc:sqlite:C:/work/mydatabase.db");  
        //Connection connection = DriverManager.getConnection("jdbc:sqlite:/home/leo/work/mydatabase.db");  
        //Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:");  
        return getConnection(URL + ((database == null || database.equals("")) ? TEST : database));  
    }  
 
    public static void close(Connection conn, Statement stmt, ResultSet rs) throws SQLException {  
        if (conn != null) {  
            conn.close();  
        }  
        if (stmt != null) {  
            stmt.close();  
        }  
        if (rs != null) {  
            rs.close();  
        }  
    }  
 
    public static void closeQuiet(Connection conn, Statement stmt, ResultSet rs) {  
        try {  
            if (conn != null) {  
                conn.close();  
            }  
        } catch (SQLException e) {  
            Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);  
        }  
        try {  
            if (stmt != null) {  
                stmt.close();  
            }  
        } catch (SQLException e) {  
            Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);  
        }  
        try {  
            if (rs != null) {  
                rs.close();  
            }  
        } catch (SQLException e) {  
            Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);  
        }  
    }  

package sqlite3;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;


public final class SQLite3Util {

    private final static String URL = "jdbc:sqlite:";
    private final static String TEST = "test";

    private static Connection getConnection(String url) throws SQLException {
        Connection conn = null;
        try {
            Class.forName("org.sqlite.JDBC");
            conn = DriverManager.getConnection(url);

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SQLite3Util.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            return conn;
        }
    }

    public static Connection getSQLite3Connection() throws SQLException {
        return getConnection(URL + TEST);
    }

    public static Connection getSQLite3Connection(String database) throws SQLException {
        //Here database can be database name, database file name or memory:
        //Connection connection = DriverManager.getConnection("jdbc:sqlite:C:/work/mydatabase.db");
        //Connection connection = DriverManager.getConnection("jdbc:sqlite:/home/leo/work/mydatabase.db");
        //Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:");
        return getConnection(URL + ((database == null || database.equals("")) ? TEST : database));
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) throws SQLException {
        if (conn != null) {
            conn.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (rs != null) {
            rs.close();
        }
    }

    public static void closeQuiet(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);
        }
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            Logger.getLogger(SQLite3Util.class.getName()).log(Level.WARNING, null, e);
        }
    }
}

 
SQLite3Test.java

package sqlite3;  
 
import java.sql.Statement;  
import java.sql.Connection;  
import java.sql.DatabaseMetaData;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.util.logging.Level;  
import java.util.logging.Logger;  
 
public class SQLite3Test {  
 
    /** 
     * @param args the command line arguments 
     */ 
    public static void main(String[] args) {  
        // declare and initialize database names and java.sql objects  
        Connection conn = null;  
        Statement stmt = null;  
        ResultSet rs = null;  
        String studentDB = "D:/NetBeans/NetbeansProjects/SQLite3/student.db";  
        String inmemoryDB = ":memory:";  
 
        // the dbmd is used to check what SQLite3JDBC driver provide for JDBC  
        DatabaseMetaData dbmd = null;  
 
        try {  
            // get connection to default database:test  
            conn = SQLite3Util.getSQLite3Connection();  
            if (conn == null) {  
                return;  
            }  
            dbmd = conn.getMetaData();  
            // just print information to standard console instead of output file  
            System.out.println("DatabaseProductName:" + dbmd.getDatabaseProductName());  
            System.out.println("SQLKeywords:" + dbmd.getSQLKeywords());  
            System.out.println("JDBCMajorVersion:" + dbmd.getJDBCMajorVersion());  
            System.out.println("JDBCMinorVersion:" + dbmd.getJDBCMinorVersion());  
 
            // get connection to database:D:/NetBeans/NetbeansProjects/SQLite3/student.db  
            conn = SQLite3Util.getSQLite3Connection(studentDB);  
            stmt = conn.createStatement();  
            stmt.executeUpdate("drop table if exists student.student");  
            stmt.executeUpdate("create table student(id smallint primary key, name varchar(20))");  
            stmt.executeUpdate("insert into student values(1,'zhangzhongliang')");  
            stmt.executeUpdate("insert into student values(2,'liusizhao')");  
            rs = stmt.executeQuery("select * from student");  
            int i = 1;  
            while (rs.next()) {  
                System.out.println("row no=" + i);  
                System.out.println("id=" + rs.getInt("id"));  
                System.out.println("name=" + rs.getString("name"));  
                i++;  
            }  
            stmt.executeUpdate("drop table student");  
 
            // get connection to database in memory  
            // this will not create a database data file in your disk  
            conn = SQLite3Util.getSQLite3Connection(inmemoryDB);  
            stmt = conn.createStatement();  
            stmt.executeUpdate("drop table if exists student.student");  
            stmt.executeUpdate("create table student(id smallint primary key, name varchar(20))");  
            stmt.executeUpdate("insert into student values(1,'zhangzhongliang')");  
            stmt.executeUpdate("insert into student values(2,'liusizhao')");  
            rs = stmt.executeQuery("select * from student");  
            i = 1;  
            while (rs.next()) {  
                System.out.println("row no=" + i);  
                System.out.println("id=" + rs.getInt("id"));  
                System.out.println("name=" + rs.getString("name"));  
                i++;  
            }  
            stmt.executeUpdate("drop table student");  
        } catch (SQLException ex) {  
            Logger.getLogger(SQLite3Test.class.getName()).log(Level.SEVERE, null, ex);  
        } finally {  
            SQLite3Util.closeQuiet(conn, stmt, rs);  
        }  
    }  

package sqlite3;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SQLite3Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // declare and initialize database names and java.sql objects
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String studentDB = "D:/NetBeans/NetbeansProjects/SQLite3/student.db";
        String inmemoryDB = ":memory:";

        // the dbmd is used to check what SQLite3JDBC driver provide for JDBC
        DatabaseMetaData dbmd = null;

        try {
            // get connection to default database:test
            conn = SQLite3Util.getSQLite3Connection();
            if (conn == null) {
                return;
            }
            dbmd = conn.getMetaData();
            // just print information to standard console instead of output file
            System.out.println("DatabaseProductName:" + dbmd.getDatabaseProductName());
            System.out.println("SQLKeywords:" + dbmd.getSQLKeywords());
            System.out.println("JDBCMajorVersion:" + dbmd.getJDBCMajorVersion());
            System.out.println("JDBCMinorVersion:" + dbmd.getJDBCMinorVersion());

            // get connection to database:D:/NetBeans/NetbeansProjects/SQLite3/student.db
            conn = SQLite3Util.getSQLite3Connection(studentDB);
            stmt = conn.createStatement();
            stmt.executeUpdate("drop table if exists student.student");
            stmt.executeUpdate("create table student(id smallint primary key, name varchar(20))");
            stmt.executeUpdate("insert into student values(1,'zhangzhongliang')");
            stmt.executeUpdate("insert into student values(2,'liusizhao')");
            rs = stmt.executeQuery("select * from student");
            int i = 1;
            while (rs.next()) {
                System.out.println("row no=" + i);
                System.out.println("id=" + rs.getInt("id"));
                System.out.println("name=" + rs.getString("name"));
                i++;
            }
            stmt.executeUpdate("drop table student");

            // get connection to database in memory
            // this will not create a database data file in your disk
            conn = SQLite3Util.getSQLite3Connection(inmemoryDB);
            stmt = conn.createStatement();
            stmt.executeUpdate("drop table if exists student.student");
            stmt.executeUpdate("create table student(id smallint primary key, name varchar(20))");
            stmt.executeUpdate("insert into student values(1,'zhangzhongliang')");
            stmt.executeUpdate("insert into student values(2,'liusizhao')");
            rs = stmt.executeQuery("select * from student");
            i = 1;
            while (rs.next()) {
                System.out.println("row no=" + i);
                System.out.println("id=" + rs.getInt("id"));
                System.out.println("name=" + rs.getString("name"));
                i++;
            }
            stmt.executeUpdate("drop table student");
        } catch (SQLException ex) {
            Logger.getLogger(SQLite3Test.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            SQLite3Util.closeQuiet(conn, stmt, rs);
        }
    }
}

 
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

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sunjavaduke/archive/2009/02/27/3939828.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值