首页 > 解决方案 > 将所有记录从一个数据库表转移到另一个数据库表

问题描述

我在一个数据库表中有记录,我想将所有记录转移到另一个数据库中的表中。

我当前的代码只能在同一数据库中的表之间传输。

 Statement st = conn.createStatement();
 int rows = st.executeUpdate("Insert into script(ID,Name) Select ID,Name from table1");
 if(rows==0){
 JOptionPane.showMessageDialog(null,"Nothing to transfer.");
 }else{
 JOptionPane.showMessageDialog(null,rows+" transfered successfully into script");
 }
}catch(SQLException | HeadlessException e){
JOptionPane.showMessageDialog(null,e);
}finally{
 try{
 rs.close();
 pst.close();
     }
 catch(Exception e){
     }
     } 

//and below are my database connections. 


public into_databses(){

conn = connector.db1();
conn1 = connector.db2();
}

//and I am currently using only   conn=connector.db1```

I want to modify it so that I can transfer records between tables in the different databases. thank you

标签: javasqlsqlite

解决方案


如果您使用的是 Sqlite3,则需要ATTACH DATABASE

使用目标数据库连接,运行以下语句:

ATTACH DATABASE 'other.db' AS source;
INSERT INTO main.script(ID, Name) SELECT ID, Name FROM source.table1;
DETACH source; -- optional

other.db您要从中复制的数据库的文件名在哪里。

处理重复主键等违反约束的事情留给读者作为练习 -INSERT根据您的需要,有多种方法可以处理可能对您有用或可能不适合您的事情。


推荐阅读