1. 程式人生 > >SQLite 如何實現從一個數據庫的某個表的記錄複製到另一個數據庫中

SQLite 如何實現從一個數據庫的某個表的記錄複製到另一個數據庫中

最近遇到了跨資料庫複製表中記錄問題,折騰了兩天,終於得到了解決!總結如下:

一、跨資料庫複製表中記錄

SQL語句:

--1.附加資料庫
ATTACH DATABASE T1 As A1;
--2.將A1中的記錄插入到目標資料庫的表中
Insert Into sn_info(author,tutor,years,degree,speciality) select author,tutor,years,degree,speciality from A1.title_info where author!="";

二、Java語言實現

1.安裝sqlite3.

地址https://www.sqlite.org/download.html

根據自己的環境,從官網下載最新版本的sqlite,windows下包括sqldiff、sqlite3、sqlite3_analyzer三個檔案,放在同一個資料夾內,例如我放在了D:\SQLite資料夾。

然後配置環境變數:我的電腦>右鍵屬性>高階系統設定>環境變數>系統變數,編輯PATH,將剛才建好的資料夾路徑加入進去,注意後面加個分號。

2.sqlite3命令列視窗

命令請自行百度。

3.sqlite管理器

推薦使用SQLite Expert。

4.java實現

①新建工程

②將sqlite-jdbc-3.18.0.jar(下載地址https://bitbucket.org/xerial/sqlite-jdbc/downloads/)匯入到專案的Referenced Labraries. 方法:選中該專案>右鍵>Build Path>Configure Build Path>Labraries>Add External JARs...

③編寫程式

package sqliteTest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo3 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        testattach();
    }

    public static void testattach(){

        Connection connection_historymapsdb = null;
        String sTargetDB="D:\\Database\\Test\\T.db3";
        try {
            Class.forName("org.sqlite.JDBC");
                connection_historymapsdb = DriverManager.getConnection("jdbc:sqlite:" + sTargetDB);
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (SQLException e2) {
            e2.printStackTrace();
        }
        Statement statement;
        try {
            String sDatabasetoattach="D:\\Database\\Test\\T2.db3";
            statement = connection_historymapsdb.createStatement();
            String sSQL="Attach \'" + sDatabasetoattach + "\' as T2";
            System.out.println(sSQL);
            statement.execute(sSQL);
            String sTestSQL="select count(*) from T2.title_info";
            ResultSet rs=statement.executeQuery(sTestSQL);
            int count=0;
            while(rs.next()){
            	count=rs.getInt(1);
            }
            System.out.println(count+"worked.");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

三、問題及解決辦法

1.更新sqlite的jar包到最新版本

2.卻把jdk在1.7版本以上

3.檢查編碼方式:Windows>Preferences>General>Workspace>Text file encoding

一般用utf8編碼。如果在utf8下仍然報錯,換成其他編碼方式試一下。