JAVA连接SQLite


概述

SQLite是一个进程内库,它实现了一个自足的、无服务器的、零配置的、事务性的SQL数据库引擎。SQLite的代码在公共领域,因此可以免费用于任何目的,无论是商业还是私人。SQLite是世界上部署最广泛的数据库,其应用数量之多,我们无法统计,其中包括几个备受瞩目的项目。

(这个数据库非常小,只有几百kb,且易于安装,非常适合练习和做小项目使用)

1.安装SQLite

官方页面下载SQLite,需要下载 sqlite-tools-win32-*.zipsqlite-dll-win32-*.zip 压缩文件。(dll的64位应该也可以用)

2020120808510520201208085105

博主现在使用的是3.34的版本

并在此文件夹下解压上面两个压缩文件,将得到 sqlite3.def、sqlite3.dll 和 sqlite3.exe 文件,把对应文件的位置添加到环境变量Path。

打开cmd,使用 sqlite3 命令,将显示如下结果

image-20201208085422762image-20201208085422762

注:红色的英文的意思是:连接到一个内存中的临时数据库

2.连接SQLite

在 Java 程序中使用 SQLite 之前,我们需要确保机器上已经有 SQLite JDBC Driver 驱动程序和 Java。可以查看 Java 教程了解如何在计算机上安装 Java。现在,我们来看看如何在机器上安装 SQLite JDBC 驱动程序。

下载对应版本的jar,并把它添加到对应IDE的jar路径,如果是intellij可以参考这篇文档,如果是使用cmd的可以参考此教程

jar下载链接

新建Sample.java,输入如下代码

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class Sample
    {
      public static void main(String[] args)
      {
        Connection connection = null;
        try
        {
          // create a database connection
          connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
          Statement statement = connection.createStatement();
          statement.setQueryTimeout(30);  // set timeout to 30 sec.

          statement.executeUpdate("drop table if exists person");
          statement.executeUpdate("create table person (id integer, name string)");
          statement.executeUpdate("insert into person values(1, 'leo')");
          statement.executeUpdate("insert into person values(2, 'yui')");
          ResultSet rs = statement.executeQuery("select * from person");
          while(rs.next())
          {
            // read the result set
            System.out.println("name = " + rs.getString("name"));
            System.out.println("id = " + rs.getInt("id"));
          }
        }
        catch(SQLException e)
        {
          // if the error message is "out of memory",
          // it probably means no database file is found
          System.err.println(e.getMessage());
        }
        finally
        {
          try
          {
            if(connection != null)
              connection.close();
          }
          catch(SQLException e)
          {
            // connection close failed.
            System.err.println(e.getMessage());
          }
        }
      }
    }

运行后,如果有如下输出,这说明配置成功:

image-20201208091432594image-20201208091432594

参考链接:

菜鸟


文章作者: 古客
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 古客 !
评论
 上一篇
jetbrains的IDE使用 jetbrains的IDE使用
概述 在使用了市面上大多数流行的编译器后,发现还是jetbrains家的IDE深得我心,特别是VS和VS code给我留下了极其糟糕的记忆,原因是不管是VS还是VS code的C++对于中文的支持着实糟糕,博主愣是折腾了好几天都没有解决输出
2020-12-07 古客
下一篇 
Emby入坑指南 Emby入坑指南
Emby概述 为了照顾小白,我就从最基础的开始吧。 首先,我们需要知道Emby是什么? 简单的说,Emby是观看家庭影视资源的流媒体服务器,我们可以通过安装Emby到自己的NAS/VPS/电脑中,在任意的地方观看视频。(需要有公网IP,不然
2020-11-28 古客