java - maven RESTful Web 服务项目中的 SQLite

标签 java sqlite maven web

<分区>

我是 REST-full 网络服务编程新手。我正在做一个项目,我需要能够从我的服务器获取和发布一些数据。我的计划是创建 SQLite 数据库,但我没有任何使用 Maven 的经验。此外,如果有任何其他(更简单的)方法来收集数据,我也会考虑。任何帮助都会很棒!谢谢!

最佳答案

在 Java 中,您使用 JDBC与数据库进行标准化通信的驱动程序。您选择使用 SQLLite 可能没问题(听起来您正在尝试学习 RESTful web 服务的基础知识)。对于“真实”应用程序,您可能会选择其他一些数据库,例如 PostgreSQL 或 MySQL。

Xerials sqlite-jdbc似乎是 SQLite 的 JDBC 驱动程序的流行实现。

使用 Maven,您需要做的就是向 pom.xml 添加依赖项。然后 Maven 将下载 jar 和任何必要的依赖项,并允许您在应用程序中使用它:

<dependencies>
    <dependency>
      <groupId>org.xerial</groupId>
      <artifactId>sqlite-jdbc</artifactId>
      <version>3.7.2</version>
    </dependency>
</dependencies>

有关如何设置连接和对数据库运行查询的示例,Xerial sqlite-jdbc 主页上的示例似乎是最好的起点:

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) throws ClassNotFoundException
  {
    // load the sqlite-JDBC driver using the current class loader
    Class.forName("org.sqlite.JDBC");

    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);
      }
    }
  }
}

关于java - maven RESTful Web 服务项目中的 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25956126/

相关文章:

java - 作为 Java 库提供的最好的免费 JavaScript 混淆器是什么?

android - 为什么sqlite中的getColumnIndex返回android中的列数?

java - 如何用 EditText 中的图像替换字符串?

java - 从网站下载多个图像并将它们保存在sqlite中

java - 使用 SQLite 处理 POJO 的 DAO 创建的更好模式

java - 从内部 jar 加载脚本文件

java - Intellij 需要很长时间才能执行 JUnit 测试的 Maven 目标

Maven surefire suiteXmlFile 可能性

java - 在 java (android) 中不重复生成随机数组 String[]

java - 使用 sendkeys 时,Web 驱动程序会跳过特殊字符 - "("和 "&"字符