2014-09-21 50 views
2

我是编程RESTfull Web服务的新手。我正在开发一个项目,我需要能够从服务器获取和发布一些数据。我的计划是创建SQLite数据库,但我在Maven中没有这方面的经验。另外,如果有任何其他(更简单)的方式来收集数据,我会考虑它。任何帮助将是伟大的!谢谢!maven的SQLite RESTfull Web服务项目

+0

SQLite和Maven的不完全涉及到另一个 - 一个是平面文件数据库,另一个是一个项目管理工具。您可能会要求您使用允许您写入SQLite的第三方库,该文件可以被Maven拉下,但这与Maven篇幅一样远。 – Makoto 2014-09-21 05:32:15

+0

我在找什么图书馆@Makoto?你能给我任何提示或指向一些有用的教程,我可以看看吗? – ndKan 2014-09-21 05:59:18

回答

10

在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); 
     } 
    } 
    } 
} 
+0

我应该在哪里把sample.db文件?在我的项目根? – pablobaldez 2016-03-14 21:34:48

+0

@pablobaldez这个问题的范围很大。这个答案指向一个SQLLite jdbc实现。您必须查阅文档以获取有关如何设置的信息。 – Magnilex 2016-03-15 07:40:41