2014-09-21 48 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