1. 程式人生 > >JAVA使用JDBC連線SQLITE資料庫

JAVA使用JDBC連線SQLITE資料庫

SQLITE非常小巧實用,對於一般應用的資料處理需求可以很好滿足。

JAVA如何使用JDBC連線SQLITE資料庫呢?

首先,需要下載一個sqlite-jdbc的驅動類:

https://github.com/xerial/sqlite-jdbc

將此驅動類匯入應用的類庫中,然後就可以在應用中使用SQLITE資料庫做各種操作了:

package bingword;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class BingWord extends Application {

    private final GridPane grid = new GridPane();
    private final Button btn = new Button();

    @Override
    public void start(Stage primaryStage) {

        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
                sqliteTest();
            }
        });

        grid.add(btn, 0, 0);

        Scene scene = new Scene(grid, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public void sqliteTest() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
            Statement statement = connection.createStatement();
            statement.setQueryTimeout(30);

            statement.executeUpdate("drop table if exists dictionary");
            statement.executeUpdate("create table dictionary (word string,p1 string,p2 string)");
            statement.executeUpdate("insert into dictionary values('one','wan','WAN')");
            statement.executeUpdate("insert into dictionary values('two','tu','TU')");

            ResultSet rs = statement.executeQuery("select * from dictionary");

            while (rs.next()) {
                System.out.println(rs.getString("word") + rs.getString("p1") + rs.getString("p2"));
            }

        } catch (SQLException ex) {
            Logger.getLogger(BingWord.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}