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下仍然报错,换成其他编码方式试一下。

你可能感兴趣的:(JAVA)