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() {

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

    }

}



你可能感兴趣的:(JAVA使用JDBC连接SQLITE数据库)